I am attempting to restrict products from appearing in archives/search results if a visitor is NOT LOGGED IN OR if there user Role is "Customer"
I'm using this snippet:
// Check User Role
function banks_has_user_role($check_role){
$user = wp_get_current_user();
if(in_array( $check_role, (array) $user->roles )){
return true;
}
return false;
}
// // Hide products in specific category from not logged-in users and user role customer
add_filter( 'woocommerce_product_query_tax_query', 'exclude_products_fom_unlogged_users', 10, 2 );
function exclude_products_fom_unlogged_users( $tax_query, $query ) {
global $user, $product;
if( ! is_user_logged_in() ){
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN', // or 'NOT IN' to exclude feature products
);
}
else if(banks_has_user_role('customer')){
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN', // or 'NOT IN' to exclude feature products
);
}
return $tax_query;
}
// The query
$query = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $products,
'orderby' => $orderby,
'order' => $order == 'asc' ? 'asc' : 'desc',
'tax_query' => $tax_query // <===
) );
When testing I was certain I got the not logged in state to work as featured products no longer displayed but I seem to get infinite loading now. Any advice?