是的,这是可能的。有两种方式:
1) 使用 pre_get_posts wordpress 挂钩,该挂钩在创建查询变量对象之后但在运行实际查询之前调用。所以它非常适合这种情况。我们在这里假设'Wholesale'类别的ID是'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_product_query WooCommerce 挂钩。 (我们这里仍然假设'Wholesale'类别的ID是'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 文件中,或者在自定义插件中更好。
如果您想使用类别 slug 而不是类别 ID,则必须将部分(两个数组)替换为:
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'wholesale', // your category slug (to use the slug see below)
如果您愿意和需要,可以在 if statements 中添加some woocommerce conditionals tags 以进一步限制这一点。
参考文献: