PHP Warning: call_user_func() expects parameter 1 to be a valid callback

Confused. Writing a plugin with which I have other callbacks working similarly fine. But when adding a meta box its failing on the callback with error:

PHP Warning: call_user_func() expects parameter 1 to be a valid callback, first array member is not a valid class name or object

Read More

Fairly standard error but I can’t work out why im receiving it. I have the following (stripped down) in a class.

function __construct(){     
   add_action( 'init', array( &$this, 'init' ) );
}

function init() {
   add_action('add_meta_boxes', function() { add_meta_box('model', 'Parent', array(&$this,'parent_meta_box'), 'model', 'side', 'high');});
}

function parent_meta_box( $post ) {
   // whatever happens here...
}

As far as I am aware I am doing the callback correctly with &this but nothing renders inside the metabox though it appears and I receive the above standard PHP error. Ive stripped it right back in my code down to this and its creating the meta box just won’t put anything inside it. I have put debug logging in and it doesnt reach it but gets before and after. Not sure what I am doing wrong. Any help greatly appreciated.

Related posts

1 comment

  1. $this is not defined in the scope of a closure. Change it to:

    add_action('add_meta_boxes', function() use ($this) { 
    add_meta_box('model', 'Parent', array($this,'parent_meta_box'), 'model', 'side', 'high');
    });
    

    Or better separate both and create a real method instead of a closure.

Comments are closed.