do_action inside class issue with add_meta_boxes hook

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.

Read More

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?

Related posts

Leave a Reply

1 comment

  1. your not too far off. to correct the above change to this:

    public function adding_custom_meta_boxes($class_array) {
        add_meta_box('my-meta-box', __($class_array[1]), array($this, 'render_my_meta_box'), 'page', 'normal', 'default');
    }
    
    • remove “do_action”

    do_action tells the script to perform the attached actions right now and the function add_meta_boxes has yet to load (google the load process for wp functions). Thats the whole point of add_actions / Filters!