[英]WooCommerce - Treat cart items separate if quantity is more than 1
我正在嘗試執行以下操作:
客戶將數量為“1”的產品添加到購物車(單個產品頁面上的數量字段已被刪除,因此只能添加 1 個)。
如果再次添加具有相同變體的相同產品,而不是將數量增加到“2”,它會將其添加為單獨的產品。
我設法使用下面的過濾器完成了上述操作,這是我在 WordPress 論壇上找到的。
add_filter('woocommerce_add_cart_item_data', 'force_separate_item_add', 10, 2);
function force_separate_item_add($cart_item_data, $product_id) {
$unique_cart_item_key = md5(microtime().rand()."Hi Mom!");
$cart_item_data['unique_key'] = $unique_cart_item_key;
return $cart_item_data;
}
這家伙的解釋非常好,我明白了: “當一個項目被添加到購物車時,購物車中該單個項目的“鍵”是根據要添加的項目及其關聯的元數據創建的。如果項目並且它的元數據與購物車中的另一個項目相同,那么生成的密鑰也將相同,並且購物車中已有項目的數量將簡單地增加被添加的數量” 。
上面的代碼只是簡單地添加了一個新鍵,然后購物車將它們視為單獨的條目。
我現在要做的是在通過購物車更改數量時為此找到合適的過濾器。 因此,如果客戶將數量更改為“2”,它將為“2nd”項目生成一個新密鑰並單獨處理。
我已經嘗試了幾乎所有我能找到的與“購物車”相關的過濾器,在 WooCommerce 文檔上搜索,在 woocommerce 插件文件夾中的 Sublime 上大量查找“更新購物車”、“購物車”等,但恐怕我'我不太確定要使用哪個。 我工作最多的一個是這個:
add_action('woocommerce_before_calculate_totals', 'change_cart_item_price');
function change_cart_item_price($cart_object) {
global $woocommerce;
foreach ($woocommerce->cart->cart_contents as $cart_key => $cart_item_array) {
if($cart_item_array['quantity'] > 1 ) {
$cart_item_key = md5(microtime().rand()."Hi Mom!");
$cart_item_data['unique_key'] = $cart_item_key;
$woocommerce->cart->set_quantity($cart_item_key, '1');
}
}
return $cart_object;
}
在這里,我正在遍歷購物車對象,檢查數量是否大於一,如果是,我分配了一個新鍵。 我真的不知道我是否做對了。
您的woocommerce_add_cart_item_data
過濾器對我來說是一個很好的開始。 我最終保持原樣並移至woocommerce_add_to_cart
掛鈎以手動處理。
這是目前為我工作的精簡版。
/**
* This hook runs at the end of the default add to cart processes, when you try to add an item to cart.
* If trying to add more than item to the cart, separate them into individual cart items
*
* @author Mike Hemberger <mike@bizbudding.com>
*
* @return void
*/
add_action( 'woocommerce_add_to_cart', 'mai_split_multiple_quantity_products_to_separate_cart_items', 10, 6 );
function mai_split_multiple_quantity_products_to_separate_cart_items( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
// If product has more than 1 quantity
if ( $quantity > 1 ) {
// Keep the product but set its quantity to 1
WC()->cart->set_quantity( $cart_item_key, 1 );
// Run a loop 1 less than the total quantity
for ( $i = 1; $i <= $quantity -1; $i++ ) {
/**
* Set a unique key.
* This is what actually forces the product into its own cart line item
*/
$cart_item_data['unique_key'] = md5( microtime() . rand() . "Hi Mom!" );
// Add the product as a new line item with the same variations that were passed
WC()->cart->add_to_cart( $product_id, 1, $variation_id, $variation, $cart_item_data );
}
}
}
有過濾鈎woocommerce_update_cart_validation
。
嘗試這個
參考:在 WooCommerce答案代碼中的購物車頁面上更新數量時拆分購物車項目
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.