Restricting the quantity of products based on attributes in WooCommerce can be useful for managing stock, limiting bulk purchases, or enforcing specific order rules. There are different methods to achieve this, including using custom code or plugins.
1. Using a Plugin to Restrict Quantity by Attribute
The easiest way to control quantity restrictions per product attribute is by using a plugin. Many WooCommerce inventory management plugins offer this functionality.
Steps:
-
Install a Quantity Restriction Plugin
- Go to Plugins > Add New in your WordPress dashboard.
- Search for a plugin like WooCommerce Min/Max Quantities or Product Quantity Limits for WooCommerce.
- Click Install Now, then Activate.
-
Configure Quantity Limits
- Navigate to WooCommerce > Settings > Products and find the quantity restriction options.
- Set minimum and maximum quantity limits for specific product attributes.
-
Save Settings
- After setting the quantity limits, save the changes to enforce the restrictions on checkout.
2. Adding Custom Code to Restrict Quantity by Attribute
If you prefer a custom solution without using a plugin, you can achieve this by adding a filter to your theme’s functions.php file.
Steps:
-
Open functions.php File
- Go to Appearance > Theme File Editor.
- Find and open the
functions.php
file.
-
Add the Following Code:
-
Save the File
- Click Update File to apply the changes.
This code checks if a product has a specific attribute (e.g., pa_size
) and prevents the customer from purchasing more than the allowed quantity.
3. Using WooCommerce Hooks to Enforce Quantity Limits
Another way to enforce quantity limits based on attributes is by modifying the cart validation process.
Steps:
-
Add the Following Code to functions.php:
-
Adjust Attribute Name and Quantity
- Change
'pa_color'
to your attribute slug (e.g.,'pa_size'
,'pa_weight'
). - Modify
$max_quantity = 3;
to set your preferred limit.
- Change
-
Save and Test
- Try adding more than the allowed quantity of a product with the specified attribute.
- You should see an error message preventing the purchase.
Conclusion
- Use a Plugin if you want a quick, no-code solution.
- Use Custom Code if you need a tailored solution without additional plugins.
- Modify Cart Hooks for advanced quantity restrictions based on attributes.
By implementing these methods, you can effectively restrict product quantities per attribute in WooCommerce, ensuring better stock management and compliance with your business rules.