Using has_term to check if a WordPress post is in a category

Sometimes the documentation lets us down. In WordPress, has_term($term, $taxonomy, $id) is used to check if a post has a term. The documentation says the taxonomy field is optional. It is not.

To check if a post is in a specific category, you need to use “category” as the taxonomy name. In a loop, you can use null for the $id to use the current post.

To check whether the current post is in the category of newsletters, use this:

if (has_term('newsletters', 'category', null) == 1) {
  // do something
}

Frequent visitors may know that we use the WP-Types Toolset plugins for many sites. You can add has_term as a custom function to use in conditional output in a Content Template. The above notes about has_term apply to this use too.  We use this conditional to substitute the font-awesome newspaper icon for a featured image on posts in the newsletter category in an archive for example:

 [wpv-conditional if="( has_term('newsletters', 'category', null) eq '1' )"]
<i class="fa fa-newspaper-o" aria-hidden="true" style="font-size:120px;"></i>
 [/wpv-conditional]

Similar Posts

Leave a Reply