2

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.

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

1 Answer 1

4

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.

1
  • If you use the register_meta_box_cb key when you call register_post_type(), it's just a shortcode for calling 'add_meta_boxes_' . $this->name, as shown on this page. Therefore, that callback also receives the $post argument. Dec 6, 2022 at 18:55

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.