This conditional tag enables you to target single entries assigned to a specific term for a custom taxonomy.
In this case, the taxonomy type slug is industry-type and the term is named long distance movers
add_action( 'loop_start', 'term_conditional_term_slug' );
function term_conditional_term_slug() {
$term = is_object_in_term( get_the_ID(), 'industry-type', 'long-distance-movers' );
if ( $term AND is_singular('industry') ) {
echo esc_html__( 'Hello World Using Term Slug','text-domain' );
}
}
This code prints the message Hello World on all single posts using the term long-distance movers.
It also uses the is_singular conditional tag with the custom post type named industry.
You could also write the code like this which uses the term slug 9 ( NOT wrapped in single or double quotes ( if you do this, it won’t work ):
add_action( 'loop_start', 'term_conditional_term_slug' );
function term_conditional_term_slug() {
$term = is_object_in_term( get_the_ID(), 'industry-type', 9 );
if ( $term AND is_singular('industry') ) {
echo esc_html__( 'Hello World Using Term Slug','text-domain' );
}
}
The above 2 code snippets work in your themes functions.php file however you can also use code in your single template.
Usage in Single Template
You could also remove the conditional tag from the code for the single template and add the code to your custom post type single template which in this case is named single-industry.php, industry being the name of the CPT.
add_action( 'loop_start', 'term_conditional_term_slug_single_template' );
function term_conditional_term_slug_single_template() {
$term = is_object_in_term( get_the_ID(), 'industry-type', 47 );
if ( $term ) {
echo esc_html__( 'In Moving Companies Single Template Term ID 47','text-domain' );
}
}
Exclude Post From Function
If you don’t want the content printed on a specific entry, add a condition tag to te function like this with the ID for the post which in this case is 10.
add_action( 'loop_start', 'term_conditional_long_distance_movers' );
function term_conditional_long_distance_movers() {
if ( is_single('10') )
return;
$term = is_object_in_term( get_the_ID(), 'industry-type', 'long-distance-movers' );
if ( $term AND is_singular() ) {
echo esc_html__( 'In Term Long Distance Movers','text-domain' );
}
}
Note : You will need to swap out either the term slug or term ID with your own as well as the CPT name, if used. And, swap out the text-domain with your themes text domain.
Demo Video
Shows you how to use the is_object_in_term
function to create a conditional tag which targets posts in specific terms for a specific taxonomy for any post type including custom posts types.
Leave a Reply
You must be logged in to post a comment.