Wordpress function to get top level category of a post?

Ok I ended up building my own function to get the top most level category.

// function to get the top level category object
// Usage - $top_cat = get_top_category();
// echo $top_cat->slug;

function get_top_category() {
    $cats = get_the_category(); // category object
    $top_cat_obj = array();

    foreach($cats as $cat) {
        if ($cat->parent == 0) {
            $top_cat_obj[] = $cat;  
        }
    }
    $top_cat_obj = $top_cat_obj[0];
    return $top_cat_obj;
}

Look at this helpful script: Get Top Level Parent Category Id Of a Single Post

And you can change this part:

$catParent = $cat->cat_ID;

To

$catParent = $cat->name;

To get the name of the top level category

Tags:

Wordpress