亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

基于 WooCommerce 購物車中某個類別的商品數量計數的折扣

基于 WooCommerce 購物車中某個類別的商品數量計數的折扣

PHP
皈依舞 2023-06-18 16:28:41
我有一類產品的價格都是 15 美元。當用戶從該類別購買 10 到 20 件產品時,他們應該獲得 10 美元的折扣價。當用戶購買 20+ 時,價格再次變為 5 美元。不能為用戶分配自定義角色(如批發商)。我根據另一個問題的 LoicTheAztec 代碼松散地創建了代碼,并添加了我自己的修改和代碼??雌饋響摽梢?。我沒有收到任何錯誤,但它不起作用。add_action('woocommerce_before_cart', 'check_product_category_in_cart');function check_product_category_in_cart() {    // HERE set your product categories in the array (can be IDs, slugs or names)    $categories = array('surfacing-adhesives');    $found      = false; // Initializing    $count = 0;    // Loop through cart items          foreach ( WC()->cart->get_cart() as $cart_item ) {        // If product categories is found        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {            $count++;        }    }    if (!current_user_can('wholesaler')) {        // Discounts        if ($count > 10 && $count < 20) {            // Drop the per item price            $price = 10;        } else if ($count > 20) {            // Drop the per item price            $price = 5;        } else {            // Did not qualify for volume discount        }    }}
查看完整描述

1 回答

?
楊__羊羊

TA貢獻1943條經驗 獲得超7個贊

您沒有使用正確的鉤子,并且缺少一些東西。嘗試以下操作:


add_action( 'woocommerce_before_calculate_totals', 'discounted_cart_item_price', 20, 1 );

function discounted_cart_item_price( $cart ){

    // Not for wholesaler user role

    if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) || current_user_can('wholesaler') )

        return;


    // Required since Woocommerce version 3.2 for cart items properties changes

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )

        return;


    // HERE set your product categories in the array (can be IDs, slugs or names)

    $categories = array('surfacing-adhesives');

    $categories = array('t-shirts');


    // Initializing

    $found = false;

    $count = 0;


    // 1st Loop: get category items count  

    foreach ( WC()->cart->get_cart() as $cart_item ) {

        // If product categories is found

        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {

            $count += $cart_item['quantity'];

        }

    }


    // Applying discount

    if ( $count >= 10 ) {

        // Discount calculation (Drop the per item qty price)

        $price = $count >= 20 ? 5 : 10;


        // 2nd Loop: Set discounted price  

        foreach ( WC()->cart->get_cart() as $cart_item ) {

            // If product categories is found

            if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {

                $cart_item['data']->set_price( $price );

            }

        }

    }

}

代碼進入您的活動子主題(或活動主題)的 functions.php 文件。測試和工作。


查看完整回答
反對 回復 2023-06-18
  • 1 回答
  • 0 關注
  • 178 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號