Support » Developing with WordPress » Add WordPress Meta Boxes using PHP class

  • am working a WordPress plugin and I am trying to add meta boxes to WordPress with PHP class, but it does not seem to be working. It spills an error that saying the add_meta_box function is undefined. Any ideas on how I can fix this. My code looks like below.

    class seo_pyra_register_fields {
      public function __construct() {
        add_action( 'add_meta_boxes', 'seo_pyra_register_fields' );
      public function seo_pyra_register_fields() {
        add_meta_box( 'seo_pyra-1', __( 'SEO Pyra', 'seo_pyra' ), 'seo_pyra_display_callback', 'post' );
        add_meta_box( 'seo_pyra-1', __( 'SEO Pyr', 'seo_pyra' ), 'seo_pyra_display_callback', 'page' );
    $enqueue_assets = new seo_pyra_register_fields();
Viewing 1 replies (of 1 total)
  • Moderator bcworkz


    Don’t call $enqueue_assets->seo_pyra_register_fields() directly (which in turn calls add_meta_box()) from plugin code. When plugins are loaded, WP is not yet stable. Calling it via “add_meta_boxes” action is the right way, but you’re adding your class method incorrectly.

    add_action() calls are constructed differently when class methods are used for the callback. Do it like this:
    add_action( 'add_meta_boxes', array( $this, 'seo_pyra_register_fields'));

Viewing 1 replies (of 1 total)
  • The topic ‘Add WordPress Meta Boxes using PHP class’ is closed to new replies.