Using WordPress ‘in_category()’ PHP function

The in_category() WordPress PHP function checks if the current post is within any of the given categories.

Usage

in_category( $category, $post = null );

Parameters

  • $category (int|string|int[]|string[]) – Required. Category ID, name, slug, or array of such to check against.
  • $post (int|WP_Post) – Optional. Post to check. Defaults to the current post. Default: null.

More information

See WordPress Developer Resources: in_category()

Examples

Testing the current post outside the Loop

During a request for an individual post (usually handled by the single.php template), you can test that post’s categories even before the Loop is begun. You could use this to switch templates like so:

if ( in_category('fruit') ) {
    include 'single-fruit.php';
} elseif ( in_category('vegetables') ) {
    include 'single-vegetables.php';
} else {
    // Continue with normal Loop
    if ( have_posts() ) : while ( have_posts() ) : the_post();
    // ...
}

Testing the current post within the Loop

in_category() is often used to take different actions within the Loop depending on the current post’s category.

if ( in_category( 'pachyderms' )) {
    // They have long trunks...
} elseif ( in_category( array( 'Tropical Birds', 'small-mammals' ) )) {
    // They are warm-blooded...
} else {
    // etc.
}

Check if a post is within a parent category or any of its subcategories

function post_is_in_descendant_category( $categories, $_post = null ) {
    foreach ( (array) $categories as $category ) {
        // Get the direct children
        $cats = get_categories( array( 'parent' => $category ) );
        $cats[] = get_category( $category );
        // Check against all the categories
        foreach ( $cats as $cat ) {
            if ( in_category( $cat, $_post ) )
                return true;
        }
    }
    return false;
}

Display different content based on the category

if ( in_category( 'news' ) ) {
    echo 'This is a news article.';
} elseif ( in_category( 'reviews' ) ) {
    echo 'This is a review.';
} else {
    echo 'This is a regular blog post.';
}

Check if a post is in multiple categories

$categories_to_check = array( 'category1', 'category2', 'category3' );

if ( in_category( $categories_to_check ) ) {
    echo 'This post is in one of the specified categories.';
} else {
    echo 'This post is not in any of the specified categories.';
}