WordPress Descendant of Category

WordPress’s default category structure is nice, but it lacks one major function: descendant category detection. The normal WordPress function in_category() only returns true if the current post is in the specified category, not if it’s a descendant.

This can be especially frustrating when creating different templates for different categories. You don’t want to have to add new conditional statements each time you add a subcategory. That’s why I created this function. It will detect weather the current post is either in, or a descendant of the category you specify.

1
2
3
4
5
6
7
8
9
10
11
12
function is_desc_cat($cats, $_post = null) {
  foreach ((array)$cats as $cat) {
    if (in_category($cat, $_post)) {
      return true;
    } else {
      if (!is_int($cat)) $cat = get_cat_ID($cat);
      $descendants = get_term_children($cat, 'category');
      if ($descendants && in_category($descendants, $_post)) return true;
    }
  }
  return false;
}

What this function does is it first checks if the category it’s in is the category you specified with in_category(). If not, then it uses get_term_children() to get all the sub-categories, and checks those.

Then, an example of how this function is used:

1
2
3
4
5
if (is_desc_cat("Blog")) {
  // do something if the current category is, or a descendant of Blog.
} else {
  // do something else.
}

The function argument is the category name, id, or array of name’s and id’s. For example:

1
2
3
is_desc_cat("Blog"); // Category name
is_desc_cat(25); // Category ID
is_desc_cat(array(12,"Blog",56)); // Array of category ID, name, or both

A simple enough function to get the job done. Also note that this function can be used in, or outside of the loop. To use it outside of the loop, supply the $_post argument:

1
2
3
4
5
6
7
8
// Get 5 most recent posts
$posts = get_posts(array('orderby' => "date", 'order' => "DESC", 'numberposts' => 5));
 
foreach ($posts as $post) {
  if (is_desc_cat("Blog", $post)) {
    // Do something if the post is in, or a descendant of the Blog category
  }
}

If you use this function inside the loop, there is no need to supply the $_post argument.

Enjoy

July 17th, 2009 | PHP / Wordpress

3 Responses to “WordPress Descendant of Category”

  1. However, you should change this line

    foreach ($cats as $cat) {

    to this:

    foreach ( (array) $cats as $cat ) {

    so you can use just a number.

  2. Thank you! I was about to write this myself, but you were faster! :P

Leave a Reply

Name:
Email:
Website:
Message:
SUBMIT