使用产品标签条件将小部件添加到WooCommerce侧边栏
I'm using WooCommerce on my Wordpress site as a catalogue (i.e. with the cart disabled) and I want to add widgets to the single product page sidebar based on if the product has a certain tag or not. I tried using the "Widget Logic" plugin and conditional tags, but even if I disabled all other plugins I could not get this to work anywhere on the site (i.e. including with a tagged post and the main sidebar - so not just with a tagged product in WooCommerce).
I then added the "PHP Code Widget" and added the code below in it:
<?php
if (is_product_tag( 'adexample1' )) {
echo "test1";
} elseif (is_product_tag( 'adexample2' )){
echo "test2";
} elseif (is_product_tag( 'adexample3' )){
echo "test3";
} elseif (is_product_tag( 'adexample4' )){
echo "test4";
} elseif (is_product_tag( 'adexample5' )){
echo "test5";
} else {
echo "<p>test6</p>";
}
?>
I've tested it with the tagged products and the other products, but they all return "test6" in the widget.
Can anyone see what I am doing wrong or is it possible that the product tags are not working/being recognised for some reason (permissions perhaps?). The issue is replicated in the default 2017 and basic WooCommerce themes, so it doesn't appear to be a theme issue?
Suggestions for another way of achieving this would also be appreciated?
Thanks
The conditional is_product_tag()
will not work to get a product that has a product tag, as it's used to return true when viewing a product tag archive page.
To do achieve what you want to do you need to use WordPress has_term()
conditional function with defined $taxonomy argument to 'product_tag'
, this way:
// Define BELOW your product tag ID, slug or name (or an array of values)
$term = 'adexample1';
$term2 = 'adexample2'; // ...
// HERE are your conditions with your code
if( has_term( $term, 'product_tag' ) ){
echo "test1";
} elseif( has_term( $term2, 'product_tag' ) ){
echo "test1";
} else {
echo "<p>test6</p>";
}
This should work as it works for product categories with defined $taxonomy argument to 'product_cat'
…