1

I have a coupon automatically adding to my cart on checkout. Basically; if category A and B are present apply the coupon. If the coupon is applied and both categories are no longer present (customer removed item from cart) then remove coupon.

This works great but I am having trouble setting up what I actually want which goes a step further:

if Both products A and B are present in cart apply the discount for EACH Of product A in cart. so if you have 5 Product A apply the discount 5 times. if the customer then removes one product A remove the extra coupon that was applied.

How would I achieve this? here is the current code for matching and applying the discount:

global $woocommerce;

    //create empty category array for push
    $category_array = [];
    // coupon code created in wooCommerce to apply
    $discount = 'A-bought-with-B';

    // start of the loop that fetches the cart items
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {

        $_product = $values['data'];
        $terms = get_the_terms( $_product->id, 'product_cat' );

        // find product categories and push them to the array
        foreach ($terms as $term) {
            $_categoryid = $term -> name;
            $category_name = strtolower( $_categoryid );

            // push term name to category array
            $category_array[] = $category_name;
        }
    }

    // 01
    // A Discount when purchased with B
    if ( in_array("A", $category_array) && in_array("B", $category_array) ) {

        $woocommerce->cart->add_discount( sanitize_text_field( $discount ) );

    } // if categories are not in cart, but the coupon is applied remove it
    else if ( !in_array("A", $category_array) || !in_array("B", $category_array) && $woocommerce->cart->has_discount( $sticker_coupon_code )  ) {
        $woocommerce->cart->remove_coupon( $discount );
    }
Eolis
  • 645
  • 2
  • 9
  • 22

0 Answers0