WooCommerce Prevent Repeat Purchases: Custom Code Solution

If you need to stop customers from purchasing the same product multiple times in WooCommerce, a simple solution can be implemented with the use of WooCommerce hooks. The following guide will show you how to check the cart for existing products before allowing a new product to be added, ensuring that the same item cannot be purchased again.

 

Step 1: Preventing the Same Product from Being Added
To implement this feature, you can add the following code to your theme’s functions.php file or a custom plugin. This code will prevent the customer from adding the same product to their cart if it is already present:

function prevent_repeat_purchase( $valid, $product_id, $quantity ) {
    if ( ! WC()->cart->is_empty() ) {
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            if ( $cart_item['product_id'] === $product_id ) {
                wc_add_notice( __( 'This item is already in your cart. You cannot purchase it again.', 'text-domain' ), 'error' );
                return false;
            }
        }
    }
    return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'prevent_repeat_purchase', 10, 3 );

 

Step 2: Customize the Error Message
When the user tries to add a product that is already in the cart, wc_add_notice() displays a custom error message. You can easily modify the message to better suit your store’s tone. Be sure to update ‘text-domain’ to match your theme or plugin’s text domain.

This simple feature ensures that customers won’t accidentally purchase the same product multiple times during the same session. If they attempt to do so, the system will notify them that the product is already in the cart.

 

Additional Considerations
This functionality only works while the cart is still active in the customer’s session. If the cart is emptied or the customer returns later, the product can be added to the cart again.

Make sure to thoroughly test this feature to confirm it works seamlessly with your WooCommerce setup and doesn’t conflict with other functionalities.

Leave a Comment

Your email address will not be published. Required fields are marked *

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.