0
votes

I am trying to find the parent category name when within a subcategory page on WooCommerce, i.e. I have 4 main categories.

Parent1

  • Sub 1
  • Sub 2
  • Sub 3 etc

Parent2

  • Sub 1
  • Sub 2
  • Sub 3 etc

and so on.

If I am on the list page for Sub2 which is a child of Parent1 I want to know the name of the Parent1 category.

2

2 Answers

0
votes

Try using wordpress get_ancestors function:

get_ancestors( $product_cat_id, 'product_cat' );

It will return an

Array of ancestors from lowest to highest in the hierarchy

Hope it helps!

-1
votes

First you need to get current category:

$term = get_queried_object();

Then get parent id of current category:

$parent_id = $term->parent;

Now you are ready to get parent category name:

$parent_name = $parent_id->name;

Full code with checking if you are in subcategory and output of parent category name:

if (is_subcategory()) {
  $term = get_queried_object();
  $parent_id = $term->parent;
  $parent_name = $parent_id->name;
  echo $parent_name;
}