Using WordPress ‘is_object_in_term()’ PHP function

The is_object_in_term() WordPress PHP function determines if the given object is associated with any of the given terms.

Usage

is_object_in_term( $object_id, $taxonomy, $terms )

Example:

Input: is_object_in_term( 42, 'genre', 'mystery' )

Output: true if post with ID 42 is in the ‘mystery’ genre, false otherwise.

Parameters

  • $object_id (int): ID of the object (post ID, link ID, etc.).
  • $taxonomy (string): Single taxonomy name.
  • $terms (int|string|int[]|string[], optional): Term ID, name, slug, or array of such to check against. Default: null.

More information

See WordPress Developer Resources: is_object_in_term

Examples

Check if a post is in a specific category

This code snippet checks if the current post is in the ‘News’ category and displays a message accordingly.

if ( is_object_in_term( $post->ID, 'category', 'News' ) ) {
    echo 'This post is in the News category.';
} else {
    echo 'This post is not in the News category.';
}

Check if a post has any tags

This example checks if the current post has any tags.

if ( is_object_in_term( $post->ID, 'post_tag' ) ) {
    echo 'This post has tags.';
} else {
    echo 'This post has no tags.';
}

Check if a post is in multiple terms

This code snippet checks if the current post is in the ‘Fiction’ or ‘Non-fiction’ genres.

if ( is_object_in_term( $post->ID, 'genre', array( 'Fiction', 'Non-fiction' ) ) ) {
    echo 'This post is either in the Fiction or Non-fiction genre.';
} else {
    echo 'This post is not in the Fiction or Non-fiction genre.';
}

Check if a custom post type is in a specific term

This example checks if a custom post type with ID 123 is in the ‘Science’ term of the ‘subject’ taxonomy.

if ( is_object_in_term( 123, 'subject', 'Science' ) ) {
    echo 'This custom post is in the Science subject.';
} else {
    echo 'This custom post is not in the Science subject.';
}

Check if a post is in a term by slug

This code snippet checks if the current post is in the term with the slug ‘breaking-news’.

if ( is_object_in_term( $post->ID, 'category', 'breaking-news' ) ) {
    echo 'This post is in the Breaking News category.';
} else {
    echo 'This post is not in the Breaking News category.';
}