Search code examples
phpwordpresswoocommerceproductcart

Remove add to cart button if the product is in cart on Woocommerce


How can I allow a particular product to be added once to the Cart?

Or is there a way to redirect to the cart page if the product is already in the shopping cart

I have found the solution here as it does not work

Disable Woocommerce add to cart button if the product is already in cart

How can this be done for all products instead of just an individual product?


Solution

  • This function will check to see if your product is already in the cart. If so it will redirect to the cart page. See the comment in the code if you want to redirect directly to checkout.

    Just place the following in your functions.php.

    Tested and works.

    function check_if_product_in_cart($valid, $product_id, $quantity) {
        global $woocommerce;
        if($woocommerce->cart->cart_contents_count > 0){
            foreach($woocommerce->cart->get_cart() as $key => $val ) {
                $_product = $val['data'];
                if($product_id == $_product->id ) {
                    // $url = WC()->cart->get_checkout_url(); // Checkout
                    $url = wc_get_cart_url();  // Cart
                    wp_redirect($url);
                    exit;
                }
            }
        }
        return $valid;
    }
    add_filter( 'woocommerce_add_to_cart_validation', 'check_if_product_in_cart',11,3);