'Hide specific products from unlogged users based in product category 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
I've tried searching but It seems a real WooCommerce corner case.
Solution 1:[1]
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:
// 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). Tested and works.
Solution 2:[2]
This ll redirect the user if not logged in :
if (!is_user_logged_in()) {
auth_redirect();
exit;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | devseo |