Restricting WooCommerce Cart to Only Allow One Item

If you’re running a WooCommerce store and want to ensure that customers can only have one item in their cart at a time, you can achieve this by adding a filter to your functions.php file. This will empty the cart whenever a new item is added, allowing only one product to be present in the cart at any given time.

Step 1: Adding the Filter

Open your theme’s functions.php file and add the following code:

1
2
3
4
5
6
7
8
// WooCommerce Only Allow One Item on Cart
add_filter( 'woocommerce_add_to_cart_validation', 'one_cart_item_at_the_time', 10, 3 );
function one_cart_item_at_the_time( $passed, $product_id, $quantity ) {
    if ( ! WC()->cart->is_empty() ) {
        WC()->cart->empty_cart();
    }
    return $passed;
}

This code hooks into the woocommerce_add_to_cart_validation filter, which is triggered when a product is added to the cart. The one_cart_item_at_the_time function checks if the cart is not empty. If it’s not empty, the function empties the cart before allowing the new item to be added.

Step 2: Providing a Direct Checkout URL

To provide a direct checkout URL with a specific product pre-added to the cart, you can use the following URL structure:

https://yourdomain.com/checkout/?add-to-cart=[product_id]

Replace yourdomain.com with your actual domain and [product_id] with the ID of the product you want to add to the cart.

For example, if your local development environment is running on https://localhost:12006 and you want to add a product with ID 123 to the cart, the URL would be:

https://localhost:12006/checkout/?add-to-cart=123

This URL will take customers directly to the checkout page with the specified product added to their cart.

Conclusion

By implementing this code in your functions.php file and using the provided direct checkout URL structure, you can ensure that your WooCommerce store allows only one item in the cart at a time and provides a convenient way for customers to quickly proceed to checkout with their chosen product.

Remember to test this implementation thoroughly on a staging or development environment before applying it to your live store to ensure it works as expected.

0%