Using Carbon Fields within a Namespace

470 Views Asked by At

I am using a WordPress Framework and need to use Carbon Fields. The problem is that everything is within a lib directory, and then separated into more directories such as classes, functions, shortcodes, plugins, etc. these are then namespaced accordingly \ThemeName\Functions, \ThemeName\Plugins etc.

From Carbonfields documentation it says add the following lines to functions.php in the root directory

use Carbon_Fields\Container; use Carbon_Fields\Field;

But how can I use Carbon Fields from within my Plugins directory?

When I try the following, I get an error:

namespace \ThemeName\Plugins;

use Carbon_Fields\Container;
use Carbon_Fields\Field;

add_action( 'carbon_fields_register_fields', 'crb_attach_theme_options' );
function crb_attach_theme_options() {
    Container::make( 'theme_options', __( 'Theme Options' ) )
        ->add_fields( array(
            Field::make( 'text', 'crb_text', 'Text Field' ),
        ) );
}

add_action( 'after_setup_theme', 'crb_load' );
function crb_load() {
   echo get_stylesheet_directory() . '/vendor/autoload.php';
    require_once( get_stylesheet_directory() . '/vendor/autoload.php' );
    \Carbon_Fields\Carbon_Fields::boot();
}

I want to be able to put all of my Carbon Fields code within this file, but with it being in the namespace I get the error

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'crb_load' not found or invalid function name in C:\xampp64\htdocs\sophie\wp-includes\class-wp-hook.php on line 286

Otherwise, if I remove the namespace it works without a problem.

1

There are 1 best solutions below

0
On

Oh, I have just figured this out, simply needed to add __NAMESPACE__ . '\funcion_name' to the add_action https://wordpress.stackexchange.com/questions/284877/add-action-in-namespace-not-working this answer helped me.