Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add another product depending on the cart total
/**
* Add another product depending on the cart total
*/
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product_id = 2831; //replace with your product id
$found = false;
$cart_total = 30; //replace with your cart total needed to add above item
if( $woocommerce->cart->total >= $cart_total ) {
//check if product already in cart
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
$woocommerce->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
$woocommerce->cart->add_to_cart( $product_id );
}
}
}
}
@allthingsa2z

This comment has been minimized.

Copy link

@allthingsa2z allthingsa2z commented Mar 26, 2019

Do you know of a code to add a product is the cart total is below a certain dollar amount - Rather than above it? Example - If order is below $20 add a product or fee

I tried playing with that code but it doesn't seem to be working for me.

@NCleveland540

This comment has been minimized.

Copy link

@NCleveland540 NCleveland540 commented May 22, 2019

What would I add to this code if I wanted the item to delete from the cart if the user deleted a product and did not meet the cart total requirement?

@NCleveland540

This comment has been minimized.

Copy link

@NCleveland540 NCleveland540 commented Jun 7, 2019

hello,

This code is working except for one small hitch. The item adds once the cart total is met and deletes if the cart total is changed, but there is no way to manually remove the item. When I try to delete the free item from the cart, the page just refreshes and the item is still there. Any ideas?

@chantalcoolsma

This comment has been minimized.

Copy link

@chantalcoolsma chantalcoolsma commented Jul 30, 2019

This code is working except for one small hitch. The item adds once the cart total is met and deletes if the cart total is changed, but there is no way to manually remove the item. When I try to delete the free item from the cart, the page just refreshes and the item is still there. Any ideas?

Seeing the same. Item is removed, but immediately added again because it wasn't found. When you remove other items from the cart until $cart_total is reached, you can delete it. Curious about a solution too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.