Adding Free product based on other products being in Cart
-
Hi,
I’m trying to create a situation whereby wherever 2 of either Product A, or Product B are present in the Cart, then Product X is automatically added to the cart and discounted to zero.
I have sorted discounting the product to zero, however the code that I have for adding Product X isn’t quite right. It is not recognising the quantity of the product in the cart, and it’s also adding Product X on page load, or page Cart update.
The code I have so far is:
add_action( ‘init’, ‘add_product_to_cart’ );
function add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product_id = 264; // ID of product that needs to be present
$free_product_id = 679; // ID of the Free product
$found = false;//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->id == $product_id ){
$found = true;
}
}
// if product not found, add it
if ( $found )
$woocommerce->cart->add_to_cart( $free_product_id );
}
}
}Any suggestions on how I might correct this please?
Thanks
- The topic ‘Adding Free product based on other products being in Cart’ is closed to new replies.