Get the Top-Level Parent Category of a Post

The following snippet is useful if you want to get the top-level parent category in the hierarchy of a post. Add the following code to your functions.php file:


function get_top_category() {

    $cats = get_the_category();
    $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;
}

Usage: $top_cat = get_top_category(); echo $top_cat->slug;

For more on taxonomies and categories, see How to Create Custom Post Types.

Discussion
[  0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!