Did you ever need to limit purchases for a specific product or category to some customers only?
You can do it with WooCommerce by adding a snippet to your site. Let’s see an example!
Let’s say that I have two type of customers, regular customers, and resellers. All products are available to regular customers, but products from the category Music are not available for resellers.
How do I limit them from purchasing those products?
First of all, I need to create the role Reseller and add a generic capability to it, in our case
resell_product. I did this by using the plugin User Role Editor, you can check its documentation to learn how to do it.
Once I created the role, I need to write some custom code to prevent them from purchasing from the category Music. So I open my functions.php file in wp-content/themes/my-child-theme-name/ and add this code at the end of it:
On line 11 there are two checks:
current_user_can( 'resell_product' ) && in_array( 17, $categories )
The first one checks if the current logged in users is a reseller, based on a custom capability that I added to the role Reseller. The second one checks if the product is in the category with ID 17, which is the ID of the category Music, the one that I want to block the purchases for.
With this code in the file I can’t even see the Add to Cart button on the product page:
While on the Shop page I see a Read More button:
And if I click on it, I will be redirected to the Shop page without being able to buy the product.