![](/img/trans.png)
[英]Hide “remove item” from cart for a specific product in WooCommerce
[英]How to remove a specific cart item when adding to cart a specific product?
使用 WooCommerce,我想看看是否可以從購物車中刪除特定商品(從購物車中),如果購物車中有另一個特定商品。
我的網上商店有一個產品的免費版本,它為客戶提供了對網站內容的基本訪問。 付費版本將開放更多內容訪問權限。 這樣,如果免費版本已經在購物車中,並且付費版本被添加到購物車,那么免費版本將從購物車中刪除。
我嘗試查看可能的選項和插件,但它們中的大多數都有基於定價之類的條件。
是的,例如在woocommerce_add_to_cart
鈎子中掛鈎的自定義函數是可能的:
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 文件或任何插件文件中。
此代碼經過測試並有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.