Remove Product from Cart Programmatically

This snippet demonstrates how to remove a specific product from the cart programmatically, which can be useful for custom cart manipulations.

PHP

function remove_product_from_cart( $product_id ) {
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        if ( $cart_item['product_id'] == $product_id ) {
            WC()->cart->remove_cart_item( $cart_item_key );
            break;
        }
    }
}
// Usage: remove_product_from_cart( 123 );

Snippet Feedback

Did this snippet work for you? Do you have any questions about this snippet? Leave some feedback below.

Tags

Language

Did it work?

Save Snippet

Embed Snippet

To embed this snippet on your site, copy this html code and paste into your webpage. Learn more
By embedding snippets on your site, you are agreeing to our terms and conditions.

Embed Snippet

To embed this snippet on your site, copy this html code and paste into your webpage. Learn more
By embedding snippets on your site, you are agreeing to our terms and conditions.

Embed Snippet

To embed this snippet on your site, copy this html code and paste into your webpage. Learn more
By embedding snippets on your site, you are agreeing to our terms and conditions.