has_term()WP 3.1.0

Checks if the specified post is associated with the specified taxonomy terms.

The function is useful when you need to conditionally output content based on categories, tags, or custom terms. It accepts both single and multiple values — IDs, slugs, or names of terms, as well as arrays of taxonomies.

If no terms are provided for comparison, the function will check if the post has any terms assigned.

If you need to check for the presence of tags on a post, use the similar function has_tags(), and if categories (categories) - has_category().

1 time — 0.003337 sec (very slow) | 50000 times — 0.82 sec (very fast) | PHP 7.1.5, WP 4.8.1

No Hooks.

Returns

true|false. true if conditions match, otherwise false.

Usage

if( has_term( $term, $taxonomy, $post ) ){
	 ...
}
$term(string/array/int)

Terms to check for presence on the post. You can specify: name, slug, ID, or an array of these elements.

If only IDs are passed, only identifiers (term_id) will be compared.

Default: ''

$taxonomy(string)
Name of the taxonomy in which to check for terms.
Default: ''
$post(int/object)
The post to check for terms. By default, it checks the current post.
Default: null (global $post)

Examples

2

#1 Checking for multiple terms

Check whether post 59 is in the terms comedy or history, which belong to the taxonomy video:

if( has_term( ['comedy','history'], 'video', 59 ) ){
	echo "The post with ID=59 has the terms `comedy` or `history` in the `video` taxonomy";
}
1

#2 Let's check if the current post has any terms in the 'video' taxonomy:

if( has_term( '', 'video' ) ){
	echo "The post has terms in the `video` taxonomy";
}
0

#3 To properly understand the previous example, it can be written like this:

if( has_term( '', 'post_tag' ) ){
	echo "The current post has tags";
}

So, we'll just check if the current post has the regular tags that WordPress uses by default (the terms in the post_tag taxonomy). You can replace this example with the conditional tag if( has_tags() ).

0

#4 Let's check if the current post has a term triller, which is in the taxonomy video:

if( has_term( 'triller', 'video' ) ){
	echo "The post has the term `triller` in the `video` taxonomy";
}

Changelog

Since 3.1.0 Introduced.

has_term() code WP 7.0

function has_term( $term = '', $taxonomy = '', $post = null ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return false;
	}

	$r = is_object_in_term( $post->ID, $taxonomy, $term );
	if ( is_wp_error( $r ) ) {
		return false;
	}

	return $r;
}