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'

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度