在Woocommerce中,如果购物车中的商品少于30万盾,我正在尝试从购物车中自动移除礼品产品。
这是我的代码:
add_action( 'template_redirect', 'remove_product_from_cart' );
function remove_product_from_cart() {
// Run only in the Cart or Checkout Page
global $woocommerce;
$current = WC()->cart->cart_contents_total;
$min_amount= 300000;
$prod_to_remove = 357;
if ( $current < $min_amount) {
if( is_cart() || is_checkout() ) {
// Cycle through each product in the cart
foreach( WC()->cart->cart_contents as $prod_in_cart ) {
// Get the Variation or Product ID
$prod_id = ( isset( $prod_in_cart['variation_id'] ) && $prod_in_cart['variation_id'] != 0 ) ? $prod_in_cart['variation_id'] : $prod_in_cart['product_id'];
// Check to see if IDs match
if( $prod_to_remove == $prod_id ) {
// Get it's unique ID within the Cart
$prod_unique_id = WC()->cart->generate_cart_id( $prod_id );
// Remove it from the cart by un-setting it
unset( WC()->cart->cart_contents[$prod_unique_id] );
wc_add_notice( __( 'Quà tặng của bạn đã bị xóa khỏi giỏ hàng vì ' ), 'notice' );
}
}
}
}}
但是问题在于它不适用于产品变体。
感谢您的帮助。
答案 0 :(得分:1)
更新 (以处理要删除的多个项目)。
尝试以下重新访问的代码,该代码也可以更好地与产品变体一起使用:
add_action( 'woocommerce_check_cart_items', 'conditionally_remove_specific_cart_item' );
function conditionally_remove_specific_cart_item() {
## -- Settings -- ##
$min_required = 300000; // The minimal required cart subtotal
$items_to_remove = array( 446, 27 ); // Product Ids to be removed from cart
// Only if cart subtotal is less than 300000
if( WC()->cart->cart_contents_total >= $min_required )
return;
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if( array_intersect( $items_to_remove, array( $cart_item['variation_id'], $cart_item['product_id'] ) ) ) {
// Remove cart item
WC()->cart->remove_cart_item( $cart_item_key );
// Add a custom notice
wc_add_notice( sprintf(
__( "Your gift has been removed from the cart because its requires a minimal cart amount of %s", "woocommerce" ),
$min_required ), 'notice' );
}
}
}
代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。
在购物车页面:
在结帐页面: