WordPress.org

Ready to get started?Download WordPress

Forums

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

  1. Firas
    Member
    Posted 9 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
    Member
    Posted 8 years ago #

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

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

    update_post_category_cache($postid);
    $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
    Member
    Posted 8 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

Tags