woocommerce - 如何在 Woocommerce 中的用户登录之前隐藏几个产品页面?
问题描述
我想对未注册/未登录的用户隐藏一些产品。我有以下代码。代码隐藏了整个类别,但我想隐藏一些产品。如果用户拥有产品链接并尝试打开页面,则应显示错误消息。
function my_product_query( $q ) {
// Not logged in
if ( !$is_logged_in ) {
$q->set( 'tax_query',
array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $cat, // your category slug
'operator' => 'NOT IN'
)
)
);
}
}
add_action( 'woocommerce_product_query', 'my_product_query', 10, 1 );
解决方案
首先,您可以将自定义字段添加到所有产品中,以了解该产品是针对登录用户还是未登录用户。然后,您可以使用以下代码重定向未登录的用户。
add_action('template_redirect','custom_single_product_redirect');
function custom_single_product_redirect(){
if (class_exists('WooCommerce')){
if(is_product()){
$is_loggedin = get_post_meta(get_the_ID(), 'your_meta_field_key'); //get product meta key value, assuming boolean
if($is_loggedin == 1 && !is_user_logged_in()){ //if user is not logged in and meta key is set to only for logged in users
wp_redirect(home_url('/shop/'));
exit();
}
}
}
return;
}
推荐阅读
- python - ValueError:没有足够的值来解包(预期 3,得到 2)。变压器编码器
- javascript - 如何将 JSON 解析为数组(用于 google 脚本)
- python - 为什么 TensorFlow 不支持 conv2d 的 strides = [1,0] 或 [0,1]?
- angular - Karma 模式与 Angular 项目中的任何文件都不匹配
- pine-script - Pine Script - 确定三个时间间隔之间的增量
- asp.net - 如何在现有 Asp.Net Core Angular 项目中逐步使用 Blazor WASM
- mysql - 从另一个容器访问 MySQL 容器
- kotlin - 比较 kotlin 中的日期时间
- java - Firebase Auth,在验证手机身份验证时崩溃,android
- android - 如何在扩展函数中获取 Dagger2 类属性?