WordPress.org

Ready to get started?Download WordPress

Forums

not category_parent but category_grandparent (3 posts)

  1. paulwordpress
    Member
    Posted 7 years ago #

    how do i detect if the grandparent of a category is a certain category

    so i have

    at the top level a category called 'location' (7)
    then i have a child category called 'australia'
    then inside australia i have 'sydney'

    when i tick 'sydney' i want to detact if it is a grandchild of 'location'

    sort of like:

    foreach((get_the_category()) as $cat){
    if ($cat->category_parent == 7){ echo $cat->cat_name;
    }
    }

    but with "$cat->category_grandparent" instead.

  2. paulwordpress
    Member
    Posted 7 years ago #

    nevermind, i got it!

    foreach((get_the_category()) as $cat){
    $cat_country_ID = $cat->category_parent;
    $cat_country = get_category($cat_country_ID);
    if ($cat_country->category_parent == 7){
    echo $cat->cat_name.', '.$cat_country->cat_name;
    }
    }

    gee, i'm smart :)

  3. mhdhallak
    Member
    Posted 6 years ago #

    Thank you! After a long tiresome search, your answer helped quite indirectly: to write a function that retrieve the root parent category of any category (you can have multiple level nesting in WordPress).

    For anyone who's interested, here's the function:

    <?php function get_root_parent_category($start_cat)
    {
    if ($start_cat->category_parent != 0)
    {
    $parent = get_category($start_cat->category_parent);
    return get_root_parent_category($parent);
    }
    else
    {
    return $start_cat;
    }
    }

Topic Closed

This topic has been closed to new replies.

About this Topic