問題描述
使用 WooCommerce,我想看看是否可以從購物車中刪除特定商品(如果購物車中有另一個特定商品).
With WooCommerce, I am looking to see if it's possible to remove a specific item (from cart), if another specific item is in the cart.
我的網上商店有一個產品的免費版本,讓客戶可以基本訪問網站內容.付費版本將開放更多內容訪問權限.這樣,如果免費版本已經在購物車中,并且付費版本被添加到購物車中,那么免費版本將從購物車中刪除.
My web shop has a free version of a product which gives to customer a basic access to site content. The paid version will open up more access to content. This way if the free version is already in the cart, and the paid version gets added to cart, then the free version will be removed from cart.
我嘗試查看可能的選項和插件,但其中大多數都有基于定價和類似內容的條件.
I tried looking at possible options and plugins but most of them have conditions based on pricing and things like that.
推薦答案
是的,例如在 woocommerce_add_to_cart
鉤子中掛鉤的自定義函數是可能的:
Yes is possible with a custom function hooked for example in woocommerce_add_to_cart
hook:
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) {
// Set HERE your targeted product ID
$target_product_id = 31;
// Set HERE the product ID to remove
$item_id_to_remove = 37;
// 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'] == $item_id_to_remove ){
$has_item = true;
$key_to_remove = $key;
}
// Check if we add to cart the targeted product ID
if( $product_id == $target_product_id ){
$is_product_id = true;
}
}
if( $has_item && $is_product_id ){
WC()->cart->remove_cart_item($key_to_remove);
// Optionaly displaying a notice for the removed item:
wc_add_notice( __( 'The product "blab bla" has been removed from cart.', 'theme_domain' ), 'notice' );
}
}
此代碼位于活動子主題(或主題)的 function.php 文件或任何插件文件中.
此代碼已經過測試且有效.
This code is tested and works.
這篇關于將特定產品添加到購物車時如何刪除特定的購物車項目?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!