WordPress: Check If a Post Belongs to a Category

WordPress provides an function to help developer 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 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 id 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';
}

Leave a Reply

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