If you want to add a product to your cart based on another product’s ID or variation or a configurable product, then this code snippet might help. Was searching how to do this until I found one in Stack Overflow. The function is based on the first code example on this website post:
https://www.tychesoftwares.com/how-to-automatically-add-a-product-to-your-woocommerce-cart-in-3-different-scenarios/
Basically, that code adds a specific product to cart based on the item’s category. So If added a product from category XYZ, then another item, a free one or not, will also be added to your woocommerce cart automatically.
But what if you want to add a product based on the options selected on a configurable product / variable product. Then the code below will help do exactly what you need
function bv_atc() {
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
$a = array(10,20,30);
$b = array(40,50,60);
if( in_array( $values['variation_id'], $a ) ) {
WC()->cart->add_to_cart(1);
} else if ( in_array( $values['variation_id'], $b ) ) {
WC()->cart->add_to_cart(2);
} else {
//if you want to do something else like adding a random item, do it here.
}
}
}
add_action( 'woocommerce_add_to_cart', 'bv_atc', 10, 2 );
Just add the code snippet to your functions.php and replace the values in the array. In my array I have two sets of items. Each item will add a different product to cart.
Just add more if conditions if you have other items that you want to be added to your cart based on the selected variations of a specific product.
Credits to Shaikh at Stackoverflow:
https://stackoverflow.com/questions/68077784/check-if-this-variation-id-exists-in-cart-then-add-another-item-to-cart
Leave a Reply