首页 > 解决方案 > 如何在 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 );

标签: woocommerce

解决方案


首先,您可以将自定义字段添加到所有产品中,以了解该产品是针对登录用户还是未登录用户。然后,您可以使用以下代码重定向未登录的用户。

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;
}

推荐阅读