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

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.

1 Answer 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.

  • I'll never understand the aversion to declaring proper callbacks. Commented Oct 15, 2013 at 12:27
  • Thanks so much made sense instantly one of those d'oh moments. I usually create real methods don't know what I decided not to this time. I should have just fallen back to previous practices. Thank you!
    – Jimbo
    Commented Oct 15, 2013 at 12:35
  • 2
    @Jimbo Note that I have removed the & from &$this. Object are always passed by reference in PHP 5. &$this is PHP 4.
    – fuxia
    Commented Oct 15, 2013 at 12:38
  • @toscho much appreciated! Already updated ;)
    – Jimbo
    Commented Oct 15, 2013 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.