0
votes

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 now want to display the content in on 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 categegory "Italian sportcars" is a child of "Cars".

Is there any way to do that?

2

2 Answers

2
votes

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.

0
votes

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.