Display metabox conditionally

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.

Leave a Comment