ALMOST THERE: We are trying to add a free/promo product to the cart when a certain cart subtotal is reached…

Everything seems to be working fine, EXCEPT with the theme we are using specifically (which is “Merchandiser” btw), when a “free/promo” item is added to the cart, the cart subtotal is multiplied by 2 showing an incorrect cart subtotal and total, apparently, this does not seem to be the case with other themes…

Is there a way to maybe automatically divide cart subtotal by 2, but ONLY when the free promo item is actually in the cart? Not sure if it is the best solution, but it should solve our problem.


Here’s the code (written by @LoicTheAztec) that we are trying to use:

add_action( 'woocommerce_before_calculate_totals', 'adding_promotional_product', 10, 1 );
function adding_promotional_product( $cart_object ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $promo_id = 2435; // <=== <=== <=== Set HERE the ID of your promotional product
    $targeted_cart_subtotal = 30; // <=== Set HERE the target cart subtotal
    $has_promo = false;
    $subtotal = 0;

    if ( !$cart_object->is_empty() ){

        // Iterating through each item in cart
        foreach ($cart_object->get_cart() as $item_key => $item_values ){

            // If Promo product is in cart
            if( $item_values['data']->id == $promo_id ) {
                $has_promo = true;
                $promo_key= $item_key;
            } else {
                // Adding subtotal item to global subtotal
                $subtotal += $item_values['line_subtotal'];
            }
        }
        // If Promo product is NOT in cart and target subtotal reached, we add it.
        if( !$has_promo && $subtotal >= $targeted_cart_subtotal ) {
            $cart_object->add_to_cart($promo_id);
            echo 'add';
        // If Promo product is in cart and target subtotal is not reached, we remove it.
        } elseif( $has_promo && $subtotal < $targeted_cart_subtotal ) {
            $cart_object->remove_cart_item($promo_key);
        }
    }
}

Read more here: ALMOST THERE: Adding a free/promo product when a certain cart subtotal is reached


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: