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.
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', // can also be 'term_id' or 'name'
'terms' => array('t-shirts'), // <=== HERE the product category slug
'operator' => 'NOT IN' // Default argument is 'IN'
);
}
return $tax_query;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.