Cray
Cray

Reputation: 5483

WooCommerce: Check if subcategory has specific parent category

I want to display content based on the current category and its parent category. To do that, I need to know if the current category is a subcategory of a specific parent category.

For example, these are my categories:

  1. Cars
    • Sportcars
      • Italian sportcars
  2. Bikes
    • Dirtbikes
      • Japanese dirtbikes

I want to display the content in every category archive down the category tree. In Cars, Sportcars and Italian sportcars for example.

For the first category I can use a Conditional Tag from WooCommerce:

is_product_category( 'cars' )

But there is no in_product_category(). So I could not check, if the category "Italian sportcars" is a child of "Cars".

Is there any way to do that?

Upvotes: 0

Views: 1343

Answers (2)

Rajeev
Rajeev

Reputation: 1488

Get the Parent Category of your category using the below code.

$parentcats = get_ancestors($product_cat_id, 'product_cat');

You will get one or more parent categories, as an array and loop over it to get the value like below:

foreach($parentcat in $parentcats){
    echo $parentcat;
}

Then you can compare it with your "Specific Category" using an IF CONDITION and do what you want.

Upvotes: 2

Eliasu
Eliasu

Reputation: 79

You can check for parent category property on the child category object. A child category has a parent property that holds the ID of its parent category. In your case the 'Italian sportcars' term object would have a parent property the points to the ID of 'Car' term.

Upvotes: 0

Related Questions