1

We're creating a plugin where, for example, it shows a metabox on all post types. To kick things off, I'm using the Starter Kit.

<?php

namespace PLUGIN_NAME;

class Foo
{
  public function __construct() {
    add_action( 'admin_init', [ $this, 'wpd_add_meta_box' ] );
  }

function wpd_add_meta_box() {
        $screens = get_post_types();
        foreach ( $screens as $screen ) {
            add_meta_box(
                'global-notice',
                __( 'Global Box 💥', 'global-box' ),
                'global_box_meta_box_callback',
                $screen,
                'advanced',
                'high'
            );
        }
    }

  function global_box_meta_box_callback( $post ) {
    echo "We're alive!"; // Never shows inside the metabox that is rendered.
  }

}

On a post page, I see the metabox but without the callback function.

Moving the code inside the functions.php, using add_action( 'admin_init','wpd_add_meta_box'), everything works fine.

How to render a metabox's content from a plugin within a class? Thanks.

3
  • That global_box_meta_box_callback() is a class method, so you need to use [ $this, 'global_box_meta_box_callback' ] when supplying the class method to add_meta_box().
    – Sally CJ
    Aug 21, 2019 at 7:26
  • 1
    Thank you soo much! You could, if you like, add this as an answer so beginners like me to see?
    – LordSylar
    Aug 21, 2019 at 7:45
  • I've just posted that as an answer. :)
    – Sally CJ
    Aug 21, 2019 at 8:06

1 Answer 1

0

That global_box_meta_box_callback() is a class method (i.e. a function inside a class) and not a globally defined function, so you need to use [ $this, 'global_box_meta_box_callback' ] (or array( $this, 'global_box_meta_box_callback' )) when supplying the class method to add_meta_box():

class Foo
{
    ...

    function wpd_add_meta_box() {
        $screens = get_post_types();
        foreach ( $screens as $screen ) {
            add_meta_box(
                'global-notice',
                __( 'Global Box 💥', 'global-box' ),
                [ $this, 'global_box_meta_box_callback' ], // correct
//              'global_box_meta_box_callback',            // incorrect
                $screen,
                'advanced',
                'high'
            );
        }
    }

    function global_box_meta_box_callback( $post ) {
        // your code here
    }
}

See the PHP manual for more details about using/supplying a callable/callback — in your case, we're using the object method call (see/find // Type 3: Object method call on that manual).

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.