WordPress: Check If a Post Belongs to a Category

WordPress provides a function to help developers check whether a post has a specific category.

has_category( string|int|array $category = '', int|object $post = null )

has_category() returns true if the referenced post has any of the given categories.

Parameters:

  • $category: it can be a category id, slug, name, or an array of them. This is the category you want to check if the post belongs to.
  • $post: post object or post if you want to check. If this function is put in The Loop, you don’t need to specify the ID.
if(has_category('development')){
  echo 'This is a Development post';
}

Another approach is to use the has_category() method

$post = get_post();
if (has_category('technology', $post)) {
    // Do something
}

In this approach, the has_category() function is used to check if the current post has the “Technology” category assigned to it. The function takes the same two parameters as in_category().

Both of these methods will return true if the post belongs to the specified category, and false if it does not.

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top