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.
in_category($category, $post = null)
$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 thehas_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.
written by Mehdi Nazari about in WordPress WordPress Plugins WordPress Themes