Aaron
Aaron

Reputation: 45

Remove specific product from WooCommerce cart only on a specific page

I'm trying to remove a specific product if it's in the cart when a customer lands on a specific page.

The Page ID is 8688 and the Product ID is 8691 (this product is a variable product, so I want to be sure regardless of the variation in the cart, the entire product is removed if it's in the cart).

This is what I came up with so far:

add_action( 'template_redirect', 'remove_product_from_cart' );
function remove_product_from_cart() {
       if( WC()->cart->is_empty() ) return;
    if( ! is_page( 8688 ) ) return;
    if ( is_admin() ) return;
    
   $product_id = 8691;
   $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 );
}

But it doesn't really works and but I feel totally lost. Appreciate any and all assistance.

Upvotes: 3

Views: 342

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254373

Try the following revisited code instead:

add_action( 'template_redirect', 'remove_product_from_cart' );
function remove_product_from_cart() {
    if( is_admin() || WC()->cart->is_empty() ) {
        return; // Exit
    }

    if ( is_page( 8688 ) ) {
        $remove_item_key     = false;
        $targeted_product_id = 8691;

        // Loop though cart items
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            if ( in_array( $targeted_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
                $remove_item_key = $cart_item_key;
                break; // Stop the loop
            }
        }

        if ( $remove_item_key ) {
            WC()->cart->remove_cart_item( $remove_item_key );
        }
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

Upvotes: 1

Related Questions