WooCommerce 根据用户角色隐藏指定分类的产品
WordPress教程
2020-12-30

我有一个客户案例需要有以下要求,需要能够将他们的WooCommerce WordPress网站分为两类,如果用户以“vip”身份登录,则只会从数据库中提取“vip”类别中的产品。但是,如果用户未登录或登录但不是“vip”用户,则不显示“vip”类别的产品。
方法一
使用在创建查询变量对象之后但在运行实际查询之前调用的pre_get_posts wordpress钩子,所以它非常适合这种情况。我们在这里想象角色名称是’VIP’,产品类别的ID是’123′。
这是自定义代码:
function wholeseller_role_cat( $query ) {
// Get the current user
$current_user = wp_get_current_user();
if ( $query->is_main_query() ) {
// Displaying only "vip" category products to "whole seller" user role
if ( in_array( 'vip', $current_user->roles ) ) {
// Set here the ID for vip category
$query->set( 'cat', '123' );
// Displaying All products (except "123" category products)
// to all other users roles (except "vip" user role)
// and to non logged user.
} else {
// Set here the ID for vip category (with minus sign before)
$query->set( 'cat', '-123' ); // negative number
}
}
}
add_action( 'pre_get_posts', 'wholeseller_role_cat' );
此代码位于子主题或主题的function.php文件中,或者页可以写到自定义插件中。
方法二
使用woocommerce_product_query WooCommerce钩子(我们仍然在这里用户角色是’vip’,产品类别的ID是’123′)
这是自定义代码:
function wholeseller_role_cat( $q ) {
// Get the current user
$current_user = wp_get_current_user();
// Displaying only "123" category products to "whole seller" user role
if ( in_array( 'vip', $current_user->roles ) ) {
// Set here the ID for vip category
$q->set( 'tax_query', array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => '123', // your category ID
)
) );
// Displaying All products (except "123" category products)
// to all other users roles (except "vip" user role)
// and to non logged user.
} else {
// Set here the ID for vip 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' );
如果要使用类别slug而不是类别ID,则必须部分替换(两个数组):
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'array( 'PUT YOUR CATEGORY HERE' ),
// your category slug (to use the slug see below)
您可以根据需要添加,在if语句中使用some woocommerce conditionals tags来限制更多。
英文演示为原版演示地址,位于境外国内访问可能比较缓慢(建议爬梯浏览),你在本站所下载的主题等源码仅供测试学习之用,如果要商用请购买 正版授权,以便获得官方的更新和售后服务。
本站承接WordPress主题安装、深度汉化、加速优化等业务,详询在线客服!
