Unable to programmatically remove product from WooCommerce cart

I’m using WooCommerce. For certain conditions, I’ll want to remove a specific product from the cart. I feel like I’m using the correct method of doing this, but for some reason it’s not working. Other system and theme-related functions appear to be working.

In the interest of complicating things less for our example here, I’ve already broken my overall attempt into the simplest form possible that I can think of. Ultimately, it’ll live as logic tucked away in a class/method in PHP within my theme. For now I’m working in functions.php solely to rule out other variables that may be causing my issue.

My primary means of testing is to refresh the cart page, which currently has the product. I’m at a loss for what else to try at this point. The end goal is to refresh the page and see the product disappear from the cart.

// ¯\_(ツ)_/¯

add_action('template_redirect', function () {
    $product_id = 29690;
    $product_cart_id = WC()->cart->generate_cart_id( $product_id );
    $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
    if ( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key );
});

Am I missing something obvious here?

Update 2020-01-03 15:32

Wanted to share that there are no errors in either the frontend console or PHP error log with debugging turned on. WooCommerce isn’t complaining or throwing an error. The page does load on refresh; but the item remains inside the cart. I haven’t been able to get it to remove programmatically with PHP using WooCommerce methods.

1 Answer
1

I guess you should use your function on the hook woocommerce_add_to_cart instead of template_redirect

Your function works fine for me. Try an alternative methow which also works:

    add_action('template_redirect', function () {
        $product_id = 29690;
        foreach( WC()->cart->get_cart() as $key=>$item){
            if($item['product_id']==$product_id){
                WC()->cart->remove_cart_item( $key );                   
            }

        }
        // $product_cart_id = WC()->cart->generate_cart_id( $product_id );
        // $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
        // if ( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key );
    });

double check your $product_id and possibly var_dump something to refine debugging

Leave a Comment