简体   繁体   English

在 WooCommerce 中隐藏未登录用户的特定产品

[英]Hide specific products from unlogged users in WooCommerce

I have a certain product category that I only want to offer to logged in users.我有一个特定的产品类别,我只想提供给登录用户。 How would I implement that?我将如何实施?

So how to hide specific products from unlogged users in WooCommerce那么如何在 WooCommerce 中隐藏未登录用户的特定产品

I've tried searching but It seems a real WooCommerce corner case.我试过搜索,但它似乎是一个真正的 WooCommerce 角落案例。

The following code will hide products from a specific product category for unlogged users only.以下代码将为未登录的用户隐藏特定产品类别中的产品。 You will have to define in the code the product category SLUG to be excluded in 'terms' array:您必须在代码中定义要排除在'terms'数组中的产品类别 SLUG:

// Hide some products from unlogged users and a specific product category
add_filter( 'woocommerce_product_query_tax_query', 'exclude_products_fom_unlogged_users', 10, 2 );
function exclude_products_fom_unlogged_users( $tax_query, $query ) {
    // On frontend for unlogged users
    if( ! is_user_logged_in() ){
        $tax_query[] = array(
            'taxonomy'  => 'product_cat',
            'field'     => 'slug',
            'terms'     => array('t-shirts'), // <=== HERE the product category slug
            'operator'  => 'NOT IN'
        );
    }
    return $tax_query;
}

Code goes in function.php file of your active child theme (or active theme).代码位于活动子主题(或活动主题)的 function.php 文件中。 Tested and works.测试和工作。

This ll redirect the user if not logged in :如果未登录,这将重定向用户:

if (!is_user_logged_in()) {
    auth_redirect();
    exit;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM