Using WordPress ‘has_category()’ PHP function

The has_category() WordPress PHP function checks if the current post has any of the given categories.

Usage

has_category( $category, $post )

Input:

has_category( 'travel', $post->ID );

Output:
true or false depending on whether the post has the ‘travel’ category.

Parameters

  • $category (string|int|array): Optional. The category name, term_id, slug, or an array of them to check for. Default is an empty string.
  • $post (int|WP_Post): Optional. The post to check. Defaults to the current post. Default is null.

More information

See WordPress Developer Resources: has_category()

Examples

### 1. Check if a post has a specific category
To check if a post has the ‘travel’ category:

if ( has_category( 'travel', $post->ID ) ) {
    echo 'The post has the "travel" category.';
} else {
    echo 'The post does not have the "travel" category.';
}

Check if a post has any of the specified categories

To check if a post has either the ‘travel’ or ‘lifestyle’ category:

if ( has_category( array( 'travel', 'lifestyle' ), $post->ID ) ) {
    echo 'The post has either the "travel" or "lifestyle" category.';
} else {
    echo 'The post does not have either the "travel" or "lifestyle" category.';
}

Check if a post has a category by term ID

To check if a post has a category with the term ID 42:

if ( has_category( 42, $post->ID ) ) {
    echo 'The post has the category with term ID 42.';
} else {
    echo 'The post does not have the category with term ID 42.';
}

Check if a post has a category using a slug

To check if a post has the category with the slug ‘travel-blog’:

if ( has_category( 'travel-blog', $post->ID ) ) {
    echo 'The post has the category with the slug "travel-blog".';
} else {
    echo 'The post does not have the category with the slug "travel-blog".';
}

Check if a post has any categories

To check if a post has any categories:

if ( has_category() ) {
    echo 'The post has at least one category.';
} else {
    echo 'The post does not have any categories.';
}