duancan8382 2018-03-29 12:27
浏览 38
已采纳

显示自定义消息当购物车中有2个特定产品类别时

In Woocommerce, I'm trying to make a function that displays a message above the cart page when products with both categories are in the cart.

I'm trying to modify code that I found here but now it already shows the message when one of the categories is added instead of both:

add_action( 'woocommerce_before_cart', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {

    $special_cat2 = 'test-cat2';
    $special_cat3 = 'test-cat3';
    $bool = false;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( has_term( $special_cat2 && $special_cat3, 'product_cat', $item->id ) )
            $bool = true;
    }

    if ($bool)
        echo '<div class="cartmessage">Warning! Beware of combining these materials!</div>';
}
  • 写回答

2条回答 默认 最新

  • dongzh1988 2018-03-29 13:18
    关注

    There is some mistakes in your code like has_term() does not support 2 terms separated with && and to get the product id from cart for custom taxonomy as product categories you need $cart_item['product_id'] instead that will also work with product variations……

    To make that works when both product categories are in cart use this instead:

    add_action( 'woocommerce_before_cart', 'allclean_add_checkout_content', 12 );
    function allclean_add_checkout_content() {
    
        $product_cats = array('test-cat2','test-cat3'); 
        $found1 = $found2 = false;
    
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            // The needed working product ID is $cart_item['product_id']  <====
            if ( has_term( $product_cats[0], 'product_cat', $cart_item['product_id'] ) )
                $found1 = true;
            elseif ( has_term( $product_cats[1], 'product_cat', $cart_item['product_id'] ) )
                $found2 = true;
        }
    
        if ( $found1 && $found2 )
            echo '<div class="cartmessage">Warning! Beware of combining these materials!</div>';
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?