For a particular project, I needed WordPress to do something based on a custom post type’s custom taxonomy. WP didn’t have a built in function for checking custom taxonomies so I googled for an answer.

After looking for ways to have WordPress do a conditional test for custom taxonomies I was unsatisfied with what I found since most of the solutions involved making functions. While they do work, it was a bit too much for my use since I really only needed to check the custom post against only one custom taxonomy. And mostly because I know that there is always more than one way to skin a cat… and sometimes I really do want to find “my own solution“.

So here’s my version of the one-time, non-function way to test for a conditional taxonomy on a conditional post type, which admittedly may not be so efficient, but it works! (and if you cache, then it doesn’t really matter) First, you need to put this bit of PHP somewhere before where you need to do your conditional test:

id, 'custom_tax_name')));
if(strpos($tempvar, '[term_taxonomy_id]=101') !== false) {$customtaxis = 'y';}else{$customtaxis = 'n';}
?>

Line 2 puts all the post’s taxonomy information as a string into the $tempvar variable. Line 3 checks whether the a taxonomy with ID of 101 is in $tempvar and sets the $customtaxis variable appropriately.

To make this work for you change the following :

  • custom_tax_name to the name of your custom taxonomy (the $taxonomy variable in the register_taxonomy function)
  • 101 to the ID of the custom taxonomy you want to test
  • $tempvar and $customtaxis to whatever variables you want, if you want

Then, where ever you want to test for your custom taxonomy, use this:

if($customtaxis  == 'y') {
// if yes, whatever you want
}else{
// if not, whatever you want
}

And that’s it!

Note: This must be used inside the loop. Tested in WP version 3.1 – 3.1.3

UPDATE: Like ms-studio said, a core function that all that has been added: has_term.

Photo by JD Hancock (cc), resized.