Someguy
Someguy

Reputation: 414

How do I get the Parent Category of the current Category Im on for Custom post type Categories

If my Current Structure is as follows : product-category/accessories/face-mask/

I can get Face-Mask Writter out by just saying: echo single_cat_title( '', true );

But I want to output Accessories (Or whatever Parent there is to the current category)

Everything I find about this is extremely extensive And I quite simply just dont get half of it so wondering if someone could explain to me how this works and how u do it?

When I try to do something like:

$categoryz = get_the_category(); 
echo $categoryz[0]->cat_ID;
$topCat = get_category_parents($categoryz);

And then output topCat I get Trying to get property 'cat_ID' of non-object

Upvotes: 0

Views: 179

Answers (1)

Bhautik
Bhautik

Reputation: 11282

try using term_id or you can use get_queried_object()

$categoryz = get_the_category(); 
$topCat    = get_category_parents($categoryz[0]->term_id);

OR

$cat = get_queried_object();
$parent_cat_id = $cat->parent;

OR

$cat = get_queried_object();
$parentcats = get_ancestors( $cat->term_id, $cat->taxonomy );

Upvotes: 1

Related Questions