WooCommerce – Add companion item to cart programatically

Viewed 31

so I am working on a force sell script of sorts that would extend to our variable products (Software Licenses) and automatically tack on the maintenance subscription. So what I have done, was try to use 'woocommerce_add_to_cart' to call my function and then by defining an array, we would be able to pair the certain software with the companion from the array. However, the companion item is not being added to the cart. See attached code:

add_action( 'woocommerce_add_to_cart', 'baam_add_companion_to_cart' );
    function baam_add_companion_to_cart() {
        // Create Array of Products with Companion
        $product['dictionary'] = array(
            18997 => 19006,
        );
        // Step through cart and add Companion
        foreach(WC()->cart->get_cart() as $cart_item) {
            $product_in_cart = $cart_item['product_id'];
            if (array_key_exists($product_in_cart, $product['dictionary'])) {
                return WC()->cart->add_to_cart($product['dictionary'][$product_in_cart], $cart_item['quantity']);
            }
        }
    }

So to walk through the code. We have our $product['dictionary'] array with the ID of the product, paired with the ID of the companioned Maintenance Fee. Using the foreach loop, I was trying to walk through the cart, and for that piece of software, say there is 2 licenses, those would be added to the cart. I have also tried to have the function execute after the item(s) were added to the cart to no avail. Any support would be greatly appreciated. Thank you.

0 Answers
Related