Hide products based on user role and category


I’m working with WordPress and Woocommerce and I’d like to hide all products with a certain category from all users, except users that has a special role.

For example, let’s say I have a category called Exclusive items and I have an user role called customer exclusive. So, when the page loads, if the user isn’t of type customer exclusive I’d like to completely hide all products within the category Exclusive items. I also want to block the user from accessing those products directly via url and to prevent them to buy those products.

I’m using the plugin User Role Editor to manage the custom user role, wich is just a copy of user type customer with a different name.

I’m trying to do it with this code here but the products keep appearing on the page.

function check_user_role() {
  $user = wp_get_current_user();
  return in_array( 'customer_exclusive', $user->roles );

function get_category_id() {
  $slug = 'exclusive-items';
  return get_term_by( 'slug', $slug, 'product_cat' )->term_id;

function restrict_woocommerce_product_query( $query ) {
  if ( !check_user_role() ) {
    $query->set( 'tax_query', array(
        'taxonomy' => 'product_cat',
        'field' => 'term_id',
        'terms' => get_category_id(),
        'operator' => 'NOT IN',

add_action( 'woocommerce_product_query', 'restrict_woocommerce_product_query' );
add_action( 'pre_get_posts', 'restrict_woocommerce_product_query' );

I’m doing all of this within my own custom plugin, that changes some behaviours.

Why does it keep appearing on the page? I tried checking the code with console.log and the checks are doing it as expected. But the product keep appearing.

Is the theme a factor here? Ex.: My theme is overading the default function and using it’s own function to load products? I’m using Flatsome theme.

celsomtrindade 2 months 0 Answers 11 views 0

Leave an answer