Ok, this is a little specific. I might be missing something but since it killed me enough time , even though I found a way around it, I need to know if there’s a way to do it properly.

Basically I want to use add_meta_box (http://codex.wordpress.org/Function_Reference/add_meta_box ) inside a class.

What I am doing:

//an array variable I am trying to pass in the class to a callback function as a parameter
$the_array = array(
    'something',
    'my meta box'
);
//a class where everything happens
class some_class {
//public function that has the array and initiates the add_meta_boxes hook
    public function add_box($class_array) {
        //add meta boxes hook to add the meta box properly
        add_action('add_meta_boxes', array($this, 'adding_custom_meta_boxes'), 10, 2);
        //passing the array variable to the callback function
        do_action('add_meta_boxes',$class_array);
    }
//the callback function of the add_meta_boxes hook
    public function adding_custom_meta_boxes($class_array) {
        add_meta_box('my-meta-box', __($class_array[1]), 'render_my_meta_box', 'page', 'normal', 'default');
    }
    public function render_my_meta_box(){
        //the code to generate the html of the meta box goes here
    }
}
$class_var = new some_class();
$class_var->add_box($the_array);

I get this error:
Fatal error: Call to undefined function add_meta_box() in C:xamppht…..

but only if I use do_action to pass the variables to the hook callback function

I found a way around it with global variables, but , does anybody know a correct way of doing this?

I am trying to create the meta box from inside a class and this happens. It works well from outside a class. Anybody any ideas?

Read more here: do_action inside class issue with add_meta_boxes hook


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Related Wordpress search:

, , , ,

Wordpress related questions and answers: