WordPress: Check if post is in custom taxonomy

At the moment there’s no core conditional function for checking whether a post belongs to a taxonomy term. A bit of searching around found this WordPress Support forum post by Justin Tadlock explaining how do check against a specific taxonomy. I’ve expanded this function a little bit so that it can be used generically.

Function

/**
* Conditional function to check if post belongs to term in a custom taxonomy.
*
* @param    tax        string                taxonomy to which the term belons
* @param    term    int|string|array    attributes of shortcode
* @param    _post    int                    post id to be checked
* @return             BOOL                True if term is matched, false otherwise
*/
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

Let’s say you’ve created a custom post type called “Films” which has a custom taxonomy of “Genres” and you want to know if the current post is in the “western” genre, you would do as follows:

if (pa_in_taxonomy('genres', 'western')) {
echo "Western films are great";
} else {
// do something else
}

Note I’m using the tax/term slug, but the is_object_in_term function in use will accept term id, slug, or array of either, so you could do:

if (pa_in_taxonomy('genres', array('western', 'drama', 'comedy'))) {}
// or
if (pa_in_taxonomy('genres', array(1, 2, 3)) {}

Comments

  • Georgios

    Worked for me. Thx!

    • Excellent! I'm kind of surprised it's not in the core conditional functions. I'm sure it will be submitted soon enough, or is in the process of being submitted. I might add this to the conditional talk page on the codex.

  • Georgios

    It should be in the core for sure!

  • Hi, Great stuff, thanks!

    BTW; it should be

    if (pa_in_taxonomy('genres', 'western') ) {

    instead of

    if (pa_in_taxonomy('genres', 'western') {

  • Extremely helpful. Thank you very much. Like in_category, this should be in core.

  • Thanks a ton…works perfectly! 😀

    • Brilliant, it's great to hear this stuff helps people out there. I have to keep on posting solutions to weird issues I come across 🙂

  • Pingback: WPSmith | in_taxonomy(): Check to Determine Whether a Post Is in a Specific Custom/Builtin Taxonomy()

  • Solai Luke

    This is the interesting submit! Thanks for the idea! Using all the best Luke aka couchgool.

  • Glaudson Alcân

    Gees, you're a life saver!

    Thank you very much!

    😀

  • Mozart

    It works! Great job, man! Thanks

  • This is excellent; thanks so much for sharing! It worked perfectly.

    • Alex Leonard

      Brilliant! Glad it was of use 🙂

  • Huw Rowlands

    Thank you thank you thank you!

    • Brilliant! That’s a lovely comment to get 🙂

      Glad it was useful for you and worthy of 3(!) “thank yous”.

  • Ramon Victor

    I don’t know why this functions isn’t in the wordpress core…
    Anyway you did a good job, guy. Thanks a lot!

    • Thanks Ramon! Perhaps I should finally dive into the trac and make some suggestions 🙂

      I’d be very proud if I ever submitted a patch/update to the core. That would be incredibly awesome!

  • Scott Chandler

    This a great help to me, thank you. I am having one problem, the taxonomy I’m using has no hierarchy, just the taxonomy and then the terms. I’m trying to use this to find out if the post belongs to that taxonomy, but I get an error saying “Warning: Missing argument 2 for pa_in_taxonomy()”

    Any way this can be done with just one argument?

    • Hi Scott,

      I don’t think it should make any difference whether it’s hierarchical or not. Perhaps the function should really be called pa_in_tax_term. A post can only be in a ‘taxonomy’ if it has a term of that taxonomy applied to it.

      If you wanted to check whether the post had *any* term that was in a taxonomy, you could get an array of the taxonomies terms and pass that into the function.

      Say your taxonomy is called books, you would do:

      $books_terms = get_terms(‘books’);

      and then follow that with:

      if (pa_in_taxonomy(‘books’, $books_terms ) {}

      I think that should work. That means you’ll check whether the current post is in ANY term in the taxonomy you’re checking.

      Does that help?

      🙂

      A!

  • elba

    That’s a lifesaver, thanks for sharing. I’m not able to put an elseif between, what am I missing?

    • Hi Elba,

      I don’t see why you wouldn’t be able to put an elseif statement in there. Do you have errors enabled so you can see what’s failing?

      In theory you should be able to do

      if ( pa_in_taxonomy(‘genres’, ‘western’) ) {
      //do this
      } elseif ( pa_in_taxonomy(‘format’, ‘dvd’) ) {
      // do that
      } else {
      // do default
      }

      • elba

        Thanks, it does work, I just missed a comma… thanks again.

  • Thank you for this snippet! Worked perfectly for a large project I am working on, saving my hair from being pulled any further!

  • Just to say thank you!

  • Hey Dan,

    Sorry for the delay getting back to you. I don’t think the is_tax function will do what I’m describing here. is_tax() is specifically for checking if an archive page is in a taxonomy.

    This function is for checking if the current *post* is in a taxonomy term.

    That said, I think this is actually covered by a core function now:

    http://codex.wordpress.org/Function_Reference/has_term

    I haven’t checked this through and through but it looks like it covers the same functionality. I’ll read up on it asap and will update the post if my function is now replaceable with a core function.

    Cheers!
    Alex

  • G.Ivanov

    Saved my life! Thanks!

  • Lewis Cains

    Thanks so much for this – very helpful!!

    • Brilliant, great to hear it was useful for you 🙂

  • outlierdesign

    Thank you so very much for sharing this! EXACTLY what I needed. This really helped me a lot on my current project.

    • Fantastic! Thrilled to know this post was of use to you 🙂

  • mania

    The best code ever!

    • Wow, thanks! That’s too kind of you 🙂 And thanks for the linkback on your blog post 🙂

  • Pingback: The best code ever! | Marta Johnsson()

  • Pingback: Come creare il tag condizionale “if in taxonomy”Wpcode.net | Wpcode.net()

  • Joey Padasian

    Funnily enough, I saw Justin’s code on Friday, and used that as a placeholder and was going to expand on it today. Glad I did a quick search before I started and found this! Very handy!

  • mathieu

    Hello,

    I try to create a menu that displays tabs according to the taxonomy presented.

    The problem is that your code appears to me that the first taxonomy.

    I am in a page that lists the current post of taxonomy.

    here is my code.

    <?php if (pa_in_taxonomy('gammes-produits', 'imprimantes-de-bureau') && pa_in_taxonomy('marques-produits', 'zebra')){
    echo "Zebra“;
    }
    if (pa_in_taxonomy(‘gammes-produits’, ‘imprimantes-de-bureau’) && pa_in_taxonomy(‘marques-produits’, ‘intermec’)){
    echo “Intermec“;
    }
    ?>

    Thank you in advance for your help.

    • mathieu

      All code excuse…

      if (pa_in_taxonomy(‘gammes-produits’, ‘imprimantes-de-bureau’) && pa_in_taxonomy(‘marques-produits’, ‘zebra’)){
      echo “Zebra“;
      }
      if (pa_in_taxonomy(‘gammes-produits’, ‘imprimantes-de-bureau’) && pa_in_taxonomy(‘marques-produits’, ‘intermec’)){
      echo “Intermec“;
      }

  • dreser

    I have the problem, please help me!

    In my case:

    if (pa_in_taxonomy(‘tax1’, ‘term1’) && pa_in_taxonomy(‘tax2’, ‘term1’)){
    echo “some text test1”;
    }

    if (pa_in_taxonomy(‘tax1’, ‘term2’) && pa_in_taxonomy(‘tax2’, ‘term1’)){
    echo “some text test2”;
    }

    will show “some text test1” and “some text test2” !

    I want to show in search results only text that belong to “tax1”, “term1” or text which belong to “tax1”, “term2” depend on search, NOT both. Is it possible and how?

  • ngita

    I love it,
    And is it possible to find a post from two differents terms of two differents taxonomy? i mean : a term of a genre taxonomy and a term of an actor taxonomy?

    Thks,

    • Hi Ngita,

      If you want to query posts from multiple taxonomies that’s absolutely possible. Check the “Multiple Taxonomies” section here: http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

      If you want to check if a post belongs to multiple taxonomies, then you’ll just need to chain your conditions, eg:

      if (pa_in_taxonomy(‘genres’, array(‘western’, ‘drama’, ‘comedy’)) || pa_in_taxonomy(‘actors’, array(‘John Wayne’, ‘Clint Eastwood’)) {
      // do stuff
      }

      Obviously you’d use an && operator if you want it to validate both instead of either.

  • Charldarwin

    Thanks, I was looking for this, you saved my life!