Snippet: True in_category Conditional function

This is an advanced version of default in_category function. This function not only check for existence of post in the specified categories but also in all the subcategories down in the tree. It has same in_category parameters So you can use it in replacement of in_category.

Usage

in_category_tree('abc-category'); // second parameter not required within the loop
in_category_tree(array('category1','category2')); // use array to specify multiple categories

Snippet

function in_category_tree($cats, $post = null) {

    if ($post == null)
        global $post;
    if (!is_array($cats))
        $cats = array($cats);
    foreach ((array) $cats as $cat) {
        if (in_category($cat, $post)) {
            return true;
        } else {

            if (!is_int($cat)) {
                $cat = get_category_by_slug($cat);
                $cat = $cat->term_id;
            }

            $descendants = get_term_children($cat, 'category');

            if ($descendants && in_category_tree($descendants, $post))
                return true;
        }
    }

    return false;
}

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>