How to Check if a Post is in Specific Categories (+Example)

2.6153846153846 from 5
from 13 user
(Rate this post)
How to Check if a Post is in Specific Categories (+Example)

Checking if a post is in a specific category can help developers serve functionalities based on categories. For example, changing a post style or loading a specific file for it, when it's in a specific category. the WordPress in_category can check if a post has a category checked for it or not.

In this tutorial, we’ll try using the WordPress in_category function in a working WordPress environment.

in_category function syntax

This function gets two parameters, the first one contains the categories, and the second one is the post.

$category parameter can be an integer, string, or an array containing multiple integers and strings (int[] or string[]).

$post parameter is optional; it can be a post ID or a post object.

If you do not specify $post, WordPress will consider the current post.

The WordPress in_category function runs the has_category function under the hood.

Check if a post is in specified categories using the in_category function

In this example, we’re going to check if a post with id 1 is in the uncategorized category or not.

Change the $category to your category name, and $postId to your desired post’s id (use null for current post).

$category = "uncategorized"; //change the name
$postId = 1; //set null for current post
if(in_category($category, $postId)){
     //post is in the category


You can change the $category value to an array.

WordPress developers can use array("uncategorized") value for $category and get the same result from the above example.

What do you think about "How to Check if a Post is in Specific Categories (+Example)"?

Your rating submit was successfull.

Your rating submit was not successfull.