I’m using code that needs to display specific content on different category pages.
My categories have the following structure:
Man
- Cloth
-
- Shorts
-
-
- Shorts with pockets
-
But the code below, displays content only on the parent category (Man), and the 1st level subcategory (Cloth):
add_action( 'woocommerce_archive_description', 'add_slide_text',1 );
function add_slide_text() {
$cat = get_queried_object();
if ( is_product_category() ) {
if ( is_product_category( 'man' ) || $cat->parent === 233 ) {
echo 'Hello man';
} elseif ( is_product_category( 'woman' ) || $cat->parent === 232 ) {
echo 'Hello woman';
} else {
echo '';
}
}
}
How can I force it to display content on subcategories of a lower level? For example, in "Shorts" and "Shorts with pockets" (and possibly lower)?
Any help is appreciated.
2
Answers
You can use the WordPress function
cat_is_ancestor_of()
.Check out the docs here: https://developer.wordpress.org/reference/functions/cat_is_ancestor_of/
Basically, you give it two things: what you think is the parent category and what you expect to be the child category.
No matter how deep the hierarchy goes, it will return true.
Here’s a quick example of how you can make it work:
Just a heads up, I haven’t tested this code, so feel free to adjust it to fit your situation.
You can use
get_term_children()
WordPress function with WooCommerce product category custom taxonomy, to display a specific text from for each specific product category "man" and "woman" terms and their children as follows:Code goes in functions.php file of your child theme (or in a plugin). Tested and works.