Hello @manx89,
There’s no many details on how and where you are running this code, so I tested it using the shell from WP-CLI, and seems like it works great for product_cat
, I advise you to pass the Product ID as the last parameter of has_term()
, it should helps in case you are in a page that for some reason is passing another ID.
For example:
if ( has_term( 'beer', 'product_cat', $product->get_id() ) ) {
wc_get_template_part( 'single-product-browar' );
} else {
wc_get_template_part( 'single-product-default' );
}
I hope it helps you.
Thread Starter
manx89
(@manx89)
Hi,
sory for writing to less information. This code is in single-product.php and works good, but only for “beer” category. I would like to make it work for “beer” category and all child categories. My category tree is like this:
Beer
-Ipa
-Lager
-Scout
So for “Ipa” category “single-product-default” template is loading but I want “single-product-browar” and for each child category of “beer” parent category.
-
This reply was modified 3 years, 8 months ago by
manx89.
So for “Ipa�? category “single-product-default�? template is loading but I want “single-product-browar�? and for each child category of “beer�? parent category.
Now makes sense what’s the issue, so by default has_term()
will only look for categories linked into your product, so if you only select Ipa
and not Beer
, has_term()
will return false. This is the default behavior of has_term()
on WordPress.
If you don’t want to mark all your products in the Beer
category, you could check for all children categories of “Beer”, you can list all in the first parameter of has_term()
, like:
if ( has_term( array( 'Beer', 'Ipa', 'Lager', 'Scout' ), 'product_cat', $product->get_id() ) ) {
wc_get_template_part( 'single-product-browar' );
} else {
wc_get_template_part( 'single-product-default' );
}
You can also get all children categories from Beer
using get_term_children(), see: https://developer.wordpress.org/reference/functions/get_term_children/
Thread Starter
manx89
(@manx89)
Hi again Claudio,
I know I can list all parameter of has_term(). But it is not best solution, because if I add another term in future I must remember to add it in this code too. But if I have no choice I do that.
get_term_children() look promising, but how to modify that to make it work as sholud for me? I’m star learnig wordpress coding;/