Ниже у меня есть некоторый код, который показывает бесплатный товар в корзине при достижении общей суммы в 25 долларов. Эта часть работает правильно. Когда пользователь удаляет товар из корзины, а его стоимость составляет менее $ 25, бесплатный товар удаляется сам. У меня проблема в том, что пользователь не может вручную удалить бесплатный товар из корзины. Я хочу, чтобы у пользователя была возможность удалить бесплатный элемент, при этом общая сумма в корзине превышает 25 долларов. Ниже приведен код, который я использую для добавления и удаления бесплатного элемента.
/*
* Automatically adding the catalog to the cart when cart total amount reach to $25.
*/
function aapc_add_product_to_cart() {
global $woocommerce;
$cart_total = 25;
if ( $woocommerce->cart->total >= $cart_total ) {
if ( ! is_admin() ) {
$free_product_id = 101861; // Product Id of the free product which will get added to cart
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $free_product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $free_product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $free_product_id );
}
}
}
}
add_action( 'template_redirect', 'aapc_add_product_to_cart' );
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= 25;
$prod_to_remove = 101861;
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] );
}
}
}
}
}