I would like to check the cart for ITEM A,
if ITEM A is present add ITEM B,
if BOTH are present DO NOTHING.
I have this code below to work with. Its working but need to check if both items are in cart and not add another item. Thanks for any help.
// add item to cart on visit
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product1_id = 66;
$product2_id = 88;
$found = false;
//check if product1 is 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 == $product1_id )
$found = true;
}
// if product1 found, add product2
if ( $found )
$woocommerce->cart->add_to_cart( $product2_id );
} else {
// check for product2 here?
}
}
}
Assuming your original code works, here is how I would do it. I have renamed a variable or two for ease of reading.
$product_1_in_cart = false;
$product_2_in_cart = false;
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product1_id )
$product_1_in_cart = true;
if ( $_product->id == $product2_id )
$product_2_in_cart = true;
}
// if product 1 is in cart, and product 2 is not in cart
if ( $product_1_in_cart && !$product_2_in_cart ){
$woocommerce->cart->add_to_cart( $product2_id );
}
} else {
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.