WordPress Check If Post Is In Category
Posted by in Tips And Tricks December 26, 2011 2 Comments

Many cases in WordPress, you would like to change a little bit your design or turn on/off some features in a particular category that posts belong to. Meaning display different things on different categories.

For example, in my Timeline category, almost articles there don’t have a long introduce so the adverting banner doesn’t fix the banner (float:left). Therefore, I decide to replace that banner with a bigger banner at center position and put all content under it.

WordPress supports a function called in_category() for this. We can both check if a particular post and current post is in specified categories. The usage is very simple as below:

A particular post is in one or more categories

<?php
	$post_id = 766;
	$category = "timeline"; // or could be category id: 634
 
	if(in_category( $category, $post_id ))
	{
		// do something
	}
	else
	{
		// do some different things
	}
?>

Current post is in one or more categories

<?php
	$category = "timeline"; // or could be category id: 634
 
	if(in_category( $category ))
	{
		// do something
	}
	else
	{
		// do some different things
	}
?>

In both cases, categories specified by ID (integer), name or slug (string), or an array of these. Or check out this function on WordPress Function Reference to get more information.

In addition, we may need to use WordPress custom field to make it more flexible and fully control.

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • http://www.biztechconsultancy.co.uk/magento-development.htm Magento Development

    I have seen a very informative blog. Really I like this blog. This blog gives us very good knowledge about WordPress development.

  • http://www.ecommerce-webdeveloper.com/magento-development/ Magento Developer

    It is really nice blog with a good stuff . Will help lot of people who want a good service. It is explained very briefly but in a good way. Thanx