Function and usage of in_category() in wordpress


Answers ( 1 )


    The in_category() function in WordPress is used to determine if a specific post falls within one or more specified categories. Here's a detailed explanation of the function and its usage:

    Function Signature:

    in_category( int|string|int[]|string[] $category, int|WP_Post $post = null ): bool

    Function Purpose:

    in_category() checks if a given post is within any of the provided categories. This function is particularly useful for theme developers who want to apply specific styles or display certain content based on the category of a post.


    • The function compares the specified categories with the post's categories based on term IDs, names, and slugs.
    • Categories given as integers (int) are checked against the post's category term IDs only.
    • Before WordPress v2.5, category names were not supported.
    • Before v2.7, category slugs and multiple category checks were not supported.
    • Initially, in_category() could only be used within the WordPress Loop and with a single category. However, since v2.7, it can be used anywhere, provided a post ID or post object is supplied.


    1. $category (int|string|int[]|string[]) (required): The category or categories to check. This can be a category ID, name, slug, or an array of these.
    2. $post (int|WP_Post) (optional): The post to check. By default, it checks the current post in the loop. If a post ID or WP_Post object is provided, it checks that specific post.

    Return Value:

    • bool: Returns true if the current or specified post is in any of the given categories, otherwise returns false.

    Sample Usage:

    Basic Usage:

    To check if the current post is in category with ID 5:

    if ( in_category( 5 ) ) {
        // The post is in category 5

    Advanced Usage:

    To check if a specific post (e.g., post ID 42) is in either category ID 3, or with the slug 'news':

    if ( in_category( array( 3, 'news' ), 42 ) ) {
        // Post ID 42 is in category 3 or has the slug 'news'

    Additional Notes:

    • As of WordPress 2.7, in_category() became more versatile, allowing checks outside the Loop and with multiple categories.
    • For more information and best practices on using this and similar functions, refer to the Conditional Tags article in the WordPress Theme Developer Handbook.

    This function is essential in creating dynamic and category-specific content on WordPress sites, making it a powerful tool for theme and plugin developers.

Leave an answer