Only Allow to Buy a Product Once in WooCommerce
To restrict customers from buying a WooCommerce product more than once, you can implement a custom solution that prevents multiple purchases of the same product for a single user. This guide will walk you through the steps needed to achieve this functionality with custom code.
Why Restrict Product Purchase to Only Once?
Limiting a product to a one-time purchase can be useful in cases where exclusive or limited-access products are involved, such as memberships, courses, or unique items. It prevents duplicate purchases, ensuring that customers don’t buy the same item multiple times.
Steps to Limit a Product Purchase to Once
To only allow customers to buy a product once in WooCommerce, you’ll use functions like wc_customer_bought_product
, is_user_logged_in
, and woocommerce_is_purchasable
. Follow these steps:
Step 1: Create a Custom Function
Add the following code to your theme’s functions.php
file or a custom plugin to check whether a product has already been purchased by the logged-in user and make it non-purchasable if so.
function custom_restrict_duplicate_product_purchase($purchasable, $product_id, $user_id) { // Check if the user is logged in if (is_user_logged_in()) { // Check if the product is already purchased by the user if (wc_customer_bought_product('', $user_id, $product_id)) { $purchasable = false; } } return $purchasable; } add_filter('woocommerce_is_purchasable', 'custom_restrict_duplicate_product_purchase', 10, 3);
Explanation of the Code
The function custom_restrict_duplicate_product_purchase
does the following:
- Checks if the user is logged in using
is_user_logged_in()
. - Uses the
wc_customer_bought_product
function to see if the user has previously purchased the product. - Sets the
$purchasable
variable tofalse
if the product was previously bought by the user, making it unavailable for purchase again.
Step 2: Save Changes and Test
After adding the code, save the changes in your functions.php
file or custom plugin. Test the functionality by logging in as a user who has previously purchased the product and attempting to add it to the cart again. The product should not be purchasable a second time.
Limitations of This Solution
Note that this approach only prevents logged-in users from purchasing the product more than once. It does not restrict guest users or users creating a new account from buying the product again. Additional customization may be needed if stricter restrictions are required.
Considerations for Advanced Requirements
If you need more control, such as restricting purchases across multiple accounts or for guest users, consider using WooCommerce plugins that offer advanced purchasing rules, or consult a developer for a custom solution.