'WooCommerce automatically add variable product to cart based on another product variation

Bear with me - I'm a newbie. Here's what I'm trying to do: if [product A/variation 1] is in the cart then add [product B/variation 1].

I need help setting up a function that does the following:

  1. check to see if the required [product A/variation 1] is in the cart
  2. check to see if [product B/variation 1] is already in the cart
  3. if [product B/variation 1] is in the cart but not required [product A/variation 1] then remove it from cart
  4. if [product B/variation 1] is not in the cart and the required [product A/variation 1] is in the cart then add [product B/variation 1] to the cart

Let's start with step 1:

To check if the required product A/variation is in the cart do I use

foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
     if ( $product_A_variation_1, array($cart_item['product_id'], $cart_item['variation_id']) ) {
           $has_required = true;
     }
     } elseif ( $product_A_variation_2, array($cart_item['product_id'], $cart_item['variation_id']) ) {
           $has_required = true;
     } elseif ( $product_A_variation_3, array($cart_item['product_id'], $cart_item['variation_id']) ) {
           $has_required = true;
     } elseif ( $product_A_variation_4, array($cart_item['product_id'], $cart_item['variation_id']) ) {
           $has_required = true;
     }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source