ilDavid.com

Get top level category of a post WP function

Postato il 29 luglio 2010

Let’s say you have a post under a subcategory and you want to show only the top level category that is assigned to the post, you can use this function:

function GetTopLevelCategory() {
    $category = get_the_category();
    $parent = $category[0]->category_parent;
    while($parent > 0) {
        $idlevel = &get_category($parent);
        $cat = $idlevel->cat_ID;
        $parent = $idlevel->parent;
    }
    $name = get_the_category_by_ID($cat);
    $link = get_category_link($cat);
    print('<a href="'.$link.'">'.$name.'</a>');
}

Tags:

Lascia un Commento