2

I'm not sure if there is a solution for that but I'll ask it anyway :)

I've built a custom-post-template and a related custom-taxonomy. The taxonomy works as kind of "categories" for the custom-post-template.

The taxonomy has terms like "car, house, wood".

I use metaboxes to add custom meta-data to my custom-post-template.

I wonder if it's possible to have different metaboxes visible for different tax-terms?

e.g. When I create a new post (with my custom-post-template) and check the "car"-category I want an additional metabox to input additional data. This metabox should just appear if the post is associated with the car-term inside that taxonomy!

Is that somehow possible?

Thank you!

1 Answer 1

3

This question is possibly a duplicate of: Only show metabox when date-value in other metabox is over?

Broadly there are two ways of achieving this. Using the add_meta_boxes hook to pass two variables: post type and the post. Then add the metabox only when the post has a certain term:

add_action( 'add_meta_boxes', 'myplugin_add_my_custom_box',10,2);

function myplugin_add_my_custom_box($post_type,$post){

 //Check if post has 'car' term from 'my-tax' taxonomy. If not don't add metabox.
 if( ! has_term( 'car', 'my-tax', $post ) )
     return

 add_meta_box( 
    'myplugin_sectionid',
    __( 'My Post Section Title', 'myplugin_textdomain' ),
    'myplugin_metabox_callback',
    'event' 
);      
}

The benefit of this approach is that its more stable - doesn't rely on javascript and is less 'dirty' than simply hiding the metabox which is what the second option is. The benefit of using javascript is that you can make it 'live' (so adding the term 'car' makes the term appear, removing it makes it disappear).

Note: When hiding you will want to clear any values so that the hidden meta box doesn't post any data that you or WordPress then saves.

This method is described here: Toggle admin metabox based upon chosen page template

1
  • Great thanks! It works fine.
    – Shiplu
    Commented Apr 30, 2022 at 14:56

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.