Use Carbon Fields in an included plugin file

971 Views Asked by At

I am using the Carbon Fields plugin (not composer). I am building a large site and will have many functions to add fields to lots of different pages. I don't like to have extremely long files that make it harder to find the code for each page. If everything is in the main plugin file, it works fine. But if I try to require_once() or include() another file that contains Carbon Fields classes, I get the error: "class Container not found".

Is there a way to get the classes to be available in included files instead of everything having to be in the main file? I have searched the documentation and can find nothing on this.

2

There are 2 best solutions below

0
On BEST ANSWER

Finally figured this out for anyone else running into an issue. Each included file that requires Carbon Fields classes must have the following at the beginning of the file:

require_once(WP_PLUGIN_DIR . '/carbon-fields/carbon-fields-plugin.php');

use Carbon_Fields\Container;
use Carbon_Fields\Field;

After this, you can start your functions and such. I am adding some additional coding on the extension plugin file to ensure the Carbon Fields plugin is activated to keep things from breaking.

0
On

You can include your file directly in functions.php like this (after installing the plugin):

require_once get_template_directory() . '/assets/inc/your-file.php';

Just replace /assets/inc/ with your folder structure.

I'm guessing your real issue is not invoking a Container::make before calling Field::make and the reason you received the class error.

In other words, something like this would go in your included file:

use Carbon_Fields\Container;
use Carbon_Fields\Field;

Container::make( 'post_meta', __( 'Page Options', 'crb' ) )
    ->where( 'post_type', '=', 'page' ) // only show our new fields on pages
    ->add_fields( array(
        Field::make( 'complex', 'slider', 'Slides' )
            ->set_layout( 'tabbed-horizontal' )
            ->add_fields( array(
                Field::make( 'text', 'slider_title', __( 'Slide Title' ) ),
                Field::make( 'image', 'slider_media', __( 'Slide Media' ) )
                    ->set_type( array( 'image', 'video' ) )
            ) ),
    ) );

The Container class must be called before the Field class or you will get the error you mentioned.