When you are using a Custom Post Type with its Custom Post Taxonomies, you could need to detect if a particular category is displayed in a post. So, I write a simple WordPress shortocode you can use to detect a particular category and then display the content of the post.
To achieve that, you can add the following code in your functions.php
file:
<?php
add_shortcode( 'wp_is_category_cpt', 'wp_is_category_cpt' );
if ( ! function_exists( 'wp_is_category_cpt' ) ) {
function wp_is_category_cpt( $atts = [], $content = null )
{
global $post;
$defaults = [
'post_type' => false,
'taxonomy' => false,
'category' => false,
];
$atts = shortcode_atts( $defaults, $atts, 'wp_is_category_cpt' );
if ( empty( $atts[ 'post_type' ] ) || empty( $atts[ 'taxonomy' ] ) || empty( $atts[ 'category' ] ) ) {
return $content;
}
if ( $post->post_type === $atts[ 'post_type' ] && has_term( $atts[ 'category' ], $atts[ 'taxonomy' ] ) ) {
return $content;
}
return "";
}
}
Next, in your post content you can use:
[wp_is_category_cpt post_type="wp_cpt" taxonomy="wp_tax" category="cars"]
This content will be visible when this post is displayed
by "wp_cpt" custom post type, in the category "cars" for taxonomy "wp_tax"
[/wp_is_category_cpt]
The wp_cpt
and wp_tax
are the Custom Post Type slug id and Custom Post Taxonomy slug id. The category
argument is the category slug.