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

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

僅將 WooCommerce 可變產品的最后一個變體保留在購物車中

僅將 WooCommerce 可變產品的最后一個變體保留在購物車中

PHP
楊__羊羊 2023-08-06 15:39:40
我有 1 個具有 3 個變體的產品,并且我一次只想在購物車中添加來自同一可變產品的 1 個變體,但不想創建帶有錯誤消息和死胡同的路障。如果添加相同的產品,我想交換變體。因此,如果客戶將產品 1 變體 1 添加到購物車,然后返回并添加相同的產品但不同的變體(產品 1 變體 2),我希望該功能刪除變體 1 并添加變體 2。這是我到目前為止所想到的——我已經測試過并且它有效,但是我不知道是否有更簡單的方法或者我是否可能會破壞其他東西add_action( 'woocommerce_add_to_cart', 'check_product_added_to_cart', 10, 6 );function check_product_added_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {    // First Variation    $product_a = 5831;    // Second Variation    $product_b = 5830;    // Third Variation    $product_c = 5832;    // Initialising some variables    $has_item = false;    $is_product_id = false;    foreach( WC()->cart->get_cart() as $key => $item ){        // Check if the item to remove is in cart        if( $item['product_id'] == $product_b || $product_c ){            $has_item = true;            $key_to_remove = $key;        }        // Check if we add to cart the targeted product ID        if( $product_id == $product_a ){            $is_product_id = true;        }    }    if( $has_item && $is_product_id ){        WC()->cart->remove_cart_item($key_to_remove);    }}
查看完整描述

1 回答

?
湖上湖

TA貢獻2003條經驗 獲得超2個贊

以下僅將可變產品的最后一個變體“靜默”保留在購物車中:


add_action('woocommerce_before_calculate_totals', 'keep_last_variation_from_variable_products', 10, 1 );

function keep_last_variation_from_variable_products( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )

        return;


    $parent_ids = array();


    foreach (  $cart->get_cart() as $cart_item_key => $cart_item ) {

        // Only for product variations

        if ( $cart_item['variation_id'] > 0 ) {

            // When a variable product exist already in cart

            if( isset($parent_ids[$cart_item['product_id']]) && ! empty($parent_ids[$cart_item['product_id']]) ) {

                // Remove it

                $cart->remove_cart_item($parent_ids[$cart_item['product_id']]);

            }

            // Set in the array the cart item key for variable product id key

            $parent_ids[$cart_item['product_id']] = $cart_item_key;

        }

    }

}

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


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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