Automatically Adding an Item to Woocommerce Cart
-
So I have some code I’m using to make a free product automatically add to the cart when the user has a cart total of $25 or more. This part of the puzzle is working fine, as well as the item being removed if the total goes below $25. My issue is that the item can not be removed manually. The user has no option to choose whether or not they want the free item and when you try to click the remove button, the cart page refreshes and the item is still there. This is the code I am using:
/*
* 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] );
}
}
}
}
}
- The topic ‘Automatically Adding an Item to Woocommerce Cart’ is closed to new replies.