Да, это возможно. Существует 2 способа:
1) С помощью Wordpress hook, который вызывается после создания объекта переменной запроса, но до запуска фактического запроса. Поэтому он идеально подходит для этого случая. Представьте себе, что ID категории 'Wholesale'
- это '123'
.
Вот пользовательский код:
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');
Этот код идет на function.php файл вашей активной темы ребенка или тему, или лучше в пользовательском плагином.
2) С WooCommerce крючком woocommerce_product_query
. (Мы все еще представляем здесь, что ID 'Wholesale'
категория is '123'
).
Вот пользовательский код:
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');
Этот код идет на function.php файл вашей активной темы ребенка или тему, или лучше в пользовательском плагином.
Если вы хотите использовать категорию слизняка вместо категории ID вы должны заменить частично (как массивы) с:
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'wholesale', // your category slug (to use the slug see below)
Вы могли бы добавить, если вы хотите, и нужно, some woocommerce conditionals tags в if statements
, чтобы ограничить это еще больше.
Ссылки:
'pre_get_posts' все! Хотя я бы посоветовал не держать это в 'functions.php вашей темы и скорее переместить его в плагин. – helgatheviking
'functions.php' - это самое простое место для отбрасывания фрагментов для быстрого тестирования, но я всегда советую использовать вашу тему для функций, связанных с дисплеем, и поддерживать любой функциональный код в плагинах. – helgatheviking
Вы не должны запускать это на pre_get_posts, если вы не хотите, чтобы это выполнялось через каждый запрос. Woocommerce hook 'woocommerce_product_query' позволит вам запускать его только по запросам woocommerce. –