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

3.4 from 5
from 5 user
(Rate this post)

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.


	//register [my-post-date] shortcode
	add_shortcode( 'my-post-date', 'my_post_date_callback' );

	define [my-post-date] callback
	-> use date-format to define date format
	-> use post-id to specify a post id
	ex: [my-post-date date-format='F j, Y' post-id=1]
	function my_post_date_callback($attributes) {

		$dateFormat = '';

		$postId = null;

		//check if date-format attribute is present in shortcode
			$dateFormat = $attributes["date-format"];

		//check if post-id attribute is present in shortcode
		//and make sure value is numeric
		if(isset($attributes["post-id"]) && is_numeric($attributes["post-id"]))
			$postId = $attributes["post-id"];

		//do not use echo, just use return
		return get_the_date($dateFormat, $postId);

$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.