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

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

當定義的產品是 WooCommerce 購物車時添加折扣

當定義的產品是 WooCommerce 購物車時添加折扣

PHP
慕桂英4014372 2023-07-08 20:52:10
我試圖為兩種產品都在購物車中時設置折扣,無論其中還有其他什么產品。到目前為止,所需要的只是數組中的兩個之一。add_action( 'woocommerce_cart_calculate_fees', 'discount_for_ab_products' );function discount_for_ab_products( $cart ) {$product_ids = array(34,35);    foreach ($product_ids as $product_id => $product) {    $product_cart_id = WC()->cart->generate_cart_id( $product );    $product_ab_in_cart = WC()->cart->find_product_in_cart( $product_cart_id );    if ( $product_ab_in_cart ) {                $discount = $cart->subtotal * 0.1;        $cart->add_fee( __( 'Discount', 'woocommerce' ) , -$discount );        }    }}
查看完整描述

1 回答

?
米脂

TA貢獻1836條經驗 獲得超3個贊

請嘗試以下操作,當所有定義的產品 ID 都在購物車中時(在您的情況下是兩個),這將提供折扣:


add_action( 'woocommerce_cart_calculate_fees', 'x_products_discount' );

function x_products_discount( $cart ) {

    // Settings below

    $product_ids = array(34, 35); // <== Your defined product Ids

    $percentage  = 10; // <== discount in percentage (10% here)


    $found_ids   = array();

    

    // Loop through cart items

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

        // Loop through defined product Ids

        foreach( $product_ids as $product_id ) {

            if( in_array( $product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {

                $found_ids[$product_id] = $product_id;

                break;

            }

        }

    }

    

    // Discount part

    if( count( $found_ids ) === count( $product_ids ) ) {

        $cart->add_fee( __( 'Discount', 'woocommerce' ), -( $cart->subtotal * $percentage / 100 ) );

    }

}

代碼位于活動子主題(或活動主題)的functions.php 文件中。經過測試并有效。


查看完整回答
反對 回復 2023-07-08
  • 1 回答
  • 0 關注
  • 174 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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