0

How would I show a sidebar only if the post (a custom post type) belongs to a specific category of that custom post type?

I was looking for something like:

if ( is_singular( 'my_custom_post_type' ) && in_category( 'my_custom_post_type_category' ) ) 

but in_category doesn't seem to work. I tried with the category ID too, but no luck.

The theme uses the name class_category as the main category for this custom post type.

2

Try using has_term() which accepts a term_name, term_id, or slug to test again. You'll need to pass the post_id too, something like this:

global $post;

if( isset( $post ) && is_singular( 'my_custom_post_type' ) && has_term( 'my_custom_post_type_category', 'my_custom_taxonomy', $post->ID ) ) {
    // Code Goes Here...
}

You may also be able to use has_category() which work very similar but if I were a betting man I'd bet that that function would only work for the built-in Post Categories but still worth mentioning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.