0
votes

Lets say i am creating 10 parent categories and 2 sub categories to each parent. My Wordpress post belongs to one sub category of a particular parent category

How do i get the parent category name ONLY? i don't want subcategories names? what Wordpress code would do that?

1
Post your so far tried code.Rikesh

1 Answers

0
votes

You can try something like that, to find the top level category of your post. The post should be associated with category and subcategory, too.

//get all categories of current post
$categories = get_the_category($post->ID);

//get top level category of current post
$top_cat_obj = array();
foreach($categories as $cat) {

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

}           
$top_cat_name = $top_cat_obj[0]->name;
$top_cat_slug = $top_cat_obj[0]->slug;