我有一个客户案例需要有以下要求,需要能够将他们的 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 来限制更多。
服务范围 | 1、专业提供WordPress主题、插件汉化、优化、PHP环境配置等服务请详询在线客服 | |||
2、本站承接 WordPress、DedeCMS、ThinkPHP 等系统建站、仿站、开发、定制等服务 | ||||
3、英文模板(主题)安装费用为120元/次,汉化主题首次免费安装(二次安装30元/次) | ||||
售后时间 | 周一至周五(法定节假日除外) 10:00-22:00 | |||
免责声明 | 本站所提供的模板(主题/插件)等资源仅供学习交流,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担,有部分资源为网上收集或仿制而来,若模板侵犯了您的合法权益,请来信通知我们(Email: 2107117185@qq.com),我们会及时删除,给您带来的不便,我们深表歉意! |
此链接为英文原版演示地址,由于英文演示针对的是境外用户,机房位于境外国内访问可能比较缓慢如果长时间未显示可以尝试刷新几次。
专业提供WordPress主题安装、深度汉化、加速优化等服务,详询在线客服!
本文由 云模板 作者:PetitQ 发表,转载请注明来源!
本站承接 WordPress / DedeCMS / ThinkPHP 等
系统建站、仿站、开发、定制等业务!