In Woocommerce, I am trying to auto remove a gift product from cart if cart item is less than 300,000 dongs.
Here is my code:
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' );
}
}
}
}}
But the problem is that it does not work with product variations.
Any help is appreciated.