Hide specific products from unlogged users based in product category in WooCommerce



PHP Snippet 1:

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

PHP Snippet 2:

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