WordPress: Check if Post Belongs to Custom Taxonomy

There is currently no core function to check whether a post belongs to a taxonomy term. This can be done very easily using a function. Simply copy and paste the below code into your functions.php file:

function pa_in_taxonomy($tax, $term, $_post = NULL) {
// if neither tax nor term are specified, return false
if ( !$tax || !$term ) { return FALSE; }
// if post parameter is given, get it, otherwise use $GLOBALS to get post
if ( $_post ) {
$_post = get_post( $_post );
} else {
$_post =& $GLOBALS['post'];
}
// if no post return false
if ( !$_post ) { return FALSE; }
// check whether post matches term belongin to tax
$return = is_object_in_term( $_post->ID, $tax, $term );
// if error returned, then return false
if ( is_wp_error( $return ) ) { return FALSE; }
return $return;
}

Usage

So for example say that you have created a custom post type called “Computers” which has a custom taxonomy (categories) called “Operating Systems” and you need to know if the current post is listed within “Windows”, you would call the function like this:

if (pa_in_taxonomy('operating-systems', 'windows')) {
echo "This post is within Windows operating systems.";
} else {
// do something else
}

The above example uses the taxonomy/term slug, but you can also use the term id, slug or array of either like the following:

if (pa_in_taxonomy('genres', array('western', 'drama', 'comedy'))) {
// do something
}
// or
if (pa_in_taxonomy('genres', array(1, 2, 3)) {
// do something
}
Free Graphics, Icons, Tutorials
Free Graphics Free Christmas Vector Icon Graphics Pack 2017Free Fitness Vector Icons Graphics PackFree Camping Vector Graphics PackFree Summer Graphics PackFree File Icon PackFree Fast Food Vector Graphics
Sharing is caring...
Like & Follow
Share the love, share this page! Facebook Twitter Google Digg Reddit LinkedIn Pinterest Email
Close [X]
The Web Taylor
1000 Lakeside North Harbour Portsmouth, Hampshire PO6 3EN
02392 123358