douyuai8994 2017-01-24 21:29
浏览 51
已采纳

使用产品标签条件将小部件添加到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

  • 写回答

1条回答 默认 最新

  • dongyong3223 2017-01-25 00:05
    关注

    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'

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改