Checking if a Page has an Associated Term?
-
16-10-2019 - |
Question
I am looking for a way to do some conditional logic on terms associated with a post.
Essentially I created my own custom taxonomy for "age groups" and have created three terms for them. Kids, Teens, Adults... In the admin area I want to check the terms which apply to a specific post and on the frontend of the site within my page template I want to show a specific image if the term was associated with the post or a different one if the term was not associated.
Does anyone have a solution for this... I thought the following code example would work but it does not. (BTW - what I am doing here is changing the image based off css).
<li id="kids-<?php if ( is_term( 'Kids' , 'age_groups' ) ) {
echo 'on';
} else {echo 'off';} ?>">Kids Programs</li>
Solution
Hi @NetConstructor:
First thing, assuming your logic worked you can use the ternary operator to simplify your example:
<li id="kids-<?php echo is_term('Kids','age_groups')
? 'on' : 'off'; ?>">Kids Programs</li>
The issue seems to be that is_term()
is used to check if a term exists, not if it is associated with a particular post. I think what you really want is is_object_in_term()
(which assumes that you are in The Loop, i.e. that $post
has an appropriate value):
<li id="kids-<?php echo is_object_in_term($post->ID,'age_groups','Kids')
? 'on' : 'off'; ?>">Kids Programs</li>
P.S. Assuming is_term()
had been the right function, it has actually been deprecated; term_exists()
replaces is_term()
; just fyi.