Search code examples
phpwordpresscarbon-fieldscarbon-fields-2

use Carbon Fields in custom plugin class


I have a plugin which has no functionality so far. This is the current structure:

<?php
class Test
{
    public function __construct()
    {

    }
}

$wpTest = new Test();

I want to use the Carbon Fields WordPress plugin. After installing it I changed the structure according to the instructions from the website, only with the adaptation to OOP.

<?php
use Carbon_Fields\Container;
use Carbon_Fields\Field;

class Test
{

    public function __construct()
    {
        add_action( 'carbon_fields_register_fields', array( $this, 'crb_attach_theme_options') );
        add_action( 'after_setup_theme', array( $this , 'crb_load' ) );
    }

    public function crb_load()
    {
        require_once( 'vendor/autoload.php' );
        \Carbon_Fields\Carbon_Fields::boot();
    }

    public function crb_attach_theme_options()
    {
        Container::make( 'theme_options', __( 'Plugin Options', 'crb' ) )
            ->add_fields( array(
                Field::make( 'text', 'crb_text', 'Text Field' ),
            ) );
    }

}

$wpTest = new Test();

It does not work. How do I fix it?


Solution

  • I found the answer to my question. From the part, the problem was that I connected the vendor/autoload.php after accessing the __construct().

    An example of solving this task below

    use Carbon_Fields\Container;
    use Carbon_Fields\Field;
    
    
    
    class PluginOption
    {
    
        public function __construct()
        {
            require_once( 'vendor/autoload.php' );
            \Carbon_Fields\Carbon_Fields::boot();
            add_action( 'carbon_fields_register_fields', array( $this, 'crb_attach_theme_options') );
        }
    
        public function crb_attach_theme_options()
        {
            Container::make( 'theme_options', __( 'Plugin Option', 'crb' ) )
            ->add_fields( array(
                Field::make( 'text', 'crb_text', 'Text Field' ),
                ) );
        }
    
    }
    
    $wpTest = new PluginOption();