Check whether a post is under a category? (3 posts)

  1. Firas
    Posted 10 years ago #

    Is there a conditional function to check whether a post is *under* a certain category, even if it wasn't exactly assigned to the category (eg, I have a 'News' category, I check the 'Music' subcategory under that, now in_category($newsid) returns false).

    Or do we need to use get_the_category and do a for loop through each category and a while loop all the way up its parents and parents' parents?

  2. ringmaster
    Posted 10 years ago #

    function in_cat_hierarchy($cat, $postid = '')
    global $category_cache, $cache_categories, $post;

    if('' == $postid) $postid = $post->ID;
    $incats = array();

    $categories = $category_cache[$postid];
    foreach($categories as $category) {
    $incats[$category->cat_ID] = true;
    $incats[$category->category_nicename] = true;
    $parent = $category->category_parent;
    while($parent != 0) {
    $incats[$parent] = true;
    $incats[$cache_categories[$parent]->category_nicename] = true;
    $parent = $cache_categories[$parent]->category_parent;
    return !empty($incats[$cat]);

  3. Andrew Jacob Johnson
    Posted 9 years ago #

    any explanation about what that means or where to put it? I need the same thing.

Topic Closed

This topic has been closed to new replies.

About this Topic