Display metabox conditionally

I have searched left, right and center and believe that this does not exist as a built in option in WordPress; is there any way to, problematically, display (or not) a metabox in a custom post type edit screen depending on the content of a metakey value?

The only idea i have is to display the content of the metakey in a hidden field, retrieving it’s value with jQuery and based on its content deleting the div containing the metabox pr not.

Read More

The content of the metabox is quite resource intensive so i am looking for another solution.

Related posts

1 comment

  1. Of course…

    function generic_cb($post) {
      echo 'This is a test of the emergency callback system.';
    }
    
    add_action( 'add_meta_boxes_page', 'conditional_meta_box' );
    function conditional_meta_box($post) {
      $meta = get_post_meta($post->ID,'meta_key',true);
      if ('abc' === $meta) {
        add_meta_box(
            'emcb',
            'CB Test',
            'generic_cb',
            'page',
            'normal',
            'high'
        );
      }
    }
    

    The add_meta_boxes* hooks pass the $post variable, so use it to check the meta key in question and conditionally add the meta box. There is a generic add_meta_boxes hook that always runs, but other add_meta_boxes_CPTSLUG hooks that are limited to particular post types. My example applies only to pages.

    If your content is a resource intensive as you say, I’d look into transients.

Comments are closed.