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:
- Cars
- Sportcars
- Italian sportcars
- Sportcars
- Bikes
- Dirtbikes
- Japanese dirtbikes
- 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
Answers
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.
Get the Parent Category of your category using the below code.
You will get one or more parent categories, as an array and loop over it to get the value like below:
Then you can compare it with your “Specific Category” using an IF CONDITION and do what you want.