Reputation: 89
I'm working on WP single.php (woocommerce installed). I need to check if current page is a product page: if yes, also check if this product is in a child category of XXX.
I found this piece of code:
if ( ! function_exists( 'post_is_in_descendant_category' ) ) {
function post_is_in_descendant_category( $cats, $_post = null ) {
foreach ( (array) $cats as $cat ) {
// get_term_children() accepts integer ID only
$descendants = get_term_children( (int) $cat, 'category' );
if ( $descendants && in_category( $descendants, $_post ) )
return true;
}
return false;
}
}
This works perfectly fine on my regular pages, but not on my product pages.
Now I currently use this code:
if ( is_product() && has_term( 'XXX', 'product_cat' ) ) {
The problem is this doesn't check for child categories. Any help?
Upvotes: 0
Views: 1525
Reputation: 417
The function you are using only checks the category taxonomy. use this one on product pages. I've replace 'category' with 'product_cat' and replaced in_category
with has_term
since that only works on categories
<?php
if (!function_exists('product_is_in_descendant_category')) {
function product_is_in_descendant_category($cats, $_post = null)
{
foreach ((array)$cats as $cat) {
// get_term_children() accepts integer ID only
$descendants = get_term_children((int)$cat, 'product_cat');
if ($descendants && has_term($descendants, 'product_cat', $_post)) {
return true;
}
}
return false;
}
}
or add a third parameter to the original function that reads $tax = 'category' and replace 'category' with $tax on line 5. then when you call the function on product pages pass 'product_cat' as the third parameter. FYI doing it this way would also require you to replace in_category
with has_term
Upvotes: 1