mysticalghoul
mysticalghoul

Reputation: 672

Deleting specific products from cart page and checkout page

My WooCommerce web shop is made of a multistep add-to-cart process, that adds a free product to cart when a step is skipped.

So I would like to remove that free products from cart on checkout page, once the selecting process is done and customer is going to pay his order.

I know that I have to use the WC_Cart method remove_cart_item( $cart_item_key ) in some hook. I have tried some hooks without success, for the moment.

My free products Ids are:

$free_products_ids = array(10,52,63,85);

How can I achieve this?

Thanks

Upvotes: 1

Views: 2544

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253814

To remove cart items on cart and checkout page, I use a custom hooked function in cart and checkout pages hooks, this way:

add_action( 'woocommerce_before_cart', 'removing_the_free_cart_items');
add_action( 'woocommerce_before_checkout_form', 'removing_the_free_cart_items');
function removing_the_free_cart_items() {

    if ( !WC()->cart->is_empty() ):

        // Here your free products IDs
        $free_products = array(10,52,63,85);

        // iterating throught each cart item
        foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item){

            $cart_item_id = $cart_item['data']->id;

            // If free product is in cart, it's removed
            if( in_array($cart_item_id, $free_products) )
                WC()->cart->remove_cart_item($cart_item_key);
        }

    endif;
}

This code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

Upvotes: 1

Related Questions