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:
function wholeseller_role_cat( $query ) {
// Get the current user
$current_user = wp_get_current_user();
if ( $query->is_main_query() ) {
// Displaying only "Wholesale" category products to "whole seller" user role
if ( in_array( 'wholeseller', $current_user->roles ) ) {
// Set here the ID for Wholesale category
$query->set( 'cat', '123' );
// Displaying All products (except "Wholesale" category products)
// to all other users roles (except "wholeseller" user role)
// and to non logged user.
} else {
// Set here the ID for Wholesale category (with minus sign before)
$query->set( 'cat', '-123' ); // negative number
}
}
}
add_action( 'pre_get_posts', 'wholeseller_role_cat' );
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:
function wholeseller_role_cat( $q ) {
// Get the current user
$current_user = wp_get_current_user();
// Displaying only "Wholesale" category products to "whole seller" user role
if ( in_array( 'wholeseller', $current_user->roles ) ) {
// Set here the ID for Wholesale category
$q->set( 'tax_query', array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => '123', // your category ID
)
) );
// Displaying All products (except "Wholesale" category products)
// to all other users roles (except "wholeseller" user role)
// and to non logged user.
} else {
// Set here the ID for Wholesale category
$q->set( 'tax_query', array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => '123', // your category ID
'operator' => 'NOT IN'
)
) );
}
}
add_action( 'woocommerce_product_query', 'wholeseller_role_cat' );
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:
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'wholesale', // your category slug (to use the slug see below)
You could add if you wish and need, some woocommerce conditionals tags in the if statements
to restrict this even more.
References:
pre_get_posts
all the things!! Though I would advise not keeping this in your theme'sfunctions.php
and rather move it into a plugin. – Blunk