使用产品标签条件将小部件添加到 WooCommerce 侧边栏

Adding widgets to a WooCommerce sidebar using product tags conditions

我在我的 Wordpress 网站上使用 WooCommerce 作为目录(即禁用购物车),我想根据产品是否具有特定标签将小部件添加到单个产品页面侧边栏。我尝试使用 "Widget Logic" 插件和条件标签,但即使我禁用了所有其他插件,我也无法让它在网站的任何地方工作(即包括带标签的 post 和主侧边栏 - 所以不仅仅是 WooCommerce 中的标记产品)。

然后我添加了 "PHP Code Widget" 并在其中添加了以下代码:

    <?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>";
}
?>

我已经用带标签的产品和其他产品对其进行了测试,但它们都在小部件中 return "test6"。

任何人都可以看到我做错了什么,或者是否有可能由于某种原因(可能是权限?)working/being 无法识别产品标签。该问题在默认的 2017 和基本 WooCommerce 主题中重复出现,因此它似乎不是主题问题?

对于实现此目标的另一种方法的建议也将不胜感激?

谢谢

条件 is_product_tag() 将无法获取具有产品标签的产品,因为在查看产品标签存档页面时它习惯于 return 为真。

要实现你想做的事情,你需要使用 WordPress has_term() 条件函数,并将 $taxonomy 参数定义为 'product_tag',这样:

// 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>";
}

这应该有效,因为它适用于将 $taxonomy 参数定义为 'product_cat'

的产品类别