Search code examples
wordpresscarbon-fields

Use Carbon Fields in an included plugin file


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.


Solution

  • 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.