The has_term() WordPress PHP function checks if the current post has any of the given terms.
Usage
has_term($term, $taxonomy, $post)
Custom Example:
Input: has_term('jazz', 'genre')
Output: true or false
Parameters
$term(string|int|array) – Optional. The term name, term_id, slug, or an array of them to check for. Default:''$taxonomy(string) – Optional. Taxonomy name. Default:''$post(int|WP_Post) – Optional. Post to check. Defaults to the current post. Default:null
More information
See WordPress Developer Resources: has_term()
Examples
Check for a specific term
Check if the current post has the term ‘jazz’ in the ‘genre’ taxonomy.
if (has_term('jazz', 'genre')) {
// do something
}
Check for any term in a taxonomy
Check if the current post has any terms in the ‘genre’ taxonomy.
if (has_term('', 'genre')) {
// do something
}
Check for specific terms in an array
Check if the current post has either ‘jazz’ or ‘blues’ terms in the ‘genre’ taxonomy.
if (has_term(array('jazz', 'blues'), 'genre')) {
// do something
}
Check for term in a specific post
Check if a specific post with ID 42 has the term ‘jazz’ in the ‘genre’ taxonomy.
$post_id = 42;
if (has_term('jazz', 'genre', $post_id)) {
// do something
}
Assign a CSS class based on term
Check if a post has a term ‘action’ in the ‘hook-type’ taxonomy and assign a CSS class accordingly.
$hook_css_class = '';
if (has_term('action', 'hook-type')) {
$hook_css_class = "is-action-hook";
} else {
$hook_css_class = "is-filter-hook";
}