Skip to content
Advertisement

How do I hide WooCommerce products with a given category based on user role

I have a client with the following issue:

I need to be able to split their WooCommerce WordPress site into essentially two categories. If a user is logged in as a "Wholeseller", only products in the "Wholesale" category get pulled from the database.

However if the user is not logged in or is logged in but not a "Wholeseller", then only products without the "Wholesale" category get pulled from the database.

I figure I’ll add something like this to the theme’s functions.php file:

JavaScript

I’ve browsed around StackOverflow, but I haven’t found what I’m looking for or quite know what keywords I should be using for my searches.

Can you point me in the right direction?

Advertisement

Answer

Yes it is possible. There is 2 ways:

1) With the pre_get_posts wordpress hook that is called after the query variable object is created, but before the actual query is run. So it is perfect for this case. We imagine here that the ID of 'Wholesale' category is '123'.

Here is the custom code:

JavaScript

This code goes on function.php file of your active child theme or theme, or better in a custom plugin.


2) With the woocommerce_product_query WooCommerce hook. (We still imagine here that the ID of 'Wholesale' category is '123').

Here is the custom code:

JavaScript

This code goes on function.php file of your active child theme or theme, or better in a custom plugin.

If you want to use the category slug instead of the category ID you will have to replace partially (both arrays) with:

JavaScript

You could add if you wish and need, some woocommerce conditionals tags in the if statements to restrict this even more.

References:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement