对的,这是可能的:
使用 pre_get_posts WordPress 钩子,它在创建查询变量对象之后但在实际查询运行之前调用。所以它非常适合这种情况。我们在这里假设“管理员”类别的 ID 是“123”。
这是自定义代码:
function administrator_role_cat( $query ) {
// Get the current user
$current_user = wp_get_current_user();
if ( $query->is_main_query() ) {
// Displaying only "administrator" category products to "administrator" user role
if ( in_array( 'administrator', $current_user->roles ) ) {
// Set here the ID for administrator category
$query->set( 'cat', '123' );
// Displaying All products (except "administrator" category products)
// to all other users roles (except "administrator" user role)
// and to non logged user.
} else {
// Set here the ID for administrator category (with minus sign before)
$query->set( 'cat', '-123' ); // negative number
}
}
}
add_action( 'pre_get_posts', 'administrator_role_cat' );