I am trying to amend the following Wordpress/Woocommerce function to restrict products if the user is not logged in.
It does appear to be working and showing the message in the last part, but it does so for everyone.
I need it to only show to users that have registered and are currently logged. The initial idea was to customers who were logged in but who have made at least one purchase - but that seems impossible to do.
I did also try using is_user_logged_in() || ! current_user_can('customer') )
but that didn’t seem to work - in fact it did the opposite, showing the cannot see message for logged in users but allowed non-logged in users to see the product.
// Hide specific products from shop and archives pages
add_action( 'woocommerce_product_query', 'wcpp_hide_product' );
function wcpp_hide_product( $q ) {
// skip for main query and on admin
if ( ! $q->is_main_query() || is_admin() )
return;
// Hide specific products for unlogged users
if ( is_user_logged_in() ) {
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'term_id', // it's not 'id' but 'term_id' (or 'name' or 'slug')
'terms' => 'login-required',
'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
}
// Replace add to cart button by a disabled button on specific products in Shop and archives pages
add_filter( 'woocommerce_loop_add_to_cart_link', 'wcpp_replace_loop_add_to_cart_button', 10, 2 );
function wcpp_replace_loop_add_to_cart_button( $button, $product ) {
if ( ( is_user_logged_in() || ! current_user_can('PRIVATE_MEMBER') )
&& has_term( 'login-required', 'product_cat', $product->get_id() ) ) {;
$button = '<a class="button alt disabled">' . __( "Private", "woocommerce" ) . '</a>';
}
return $button;
}
// On single product pages, redirect to shop and display a custom notice for specific products
add_action( 'template_redirect', 'wcpp_redirect_hiding_product_detail' );
function wcpp_redirect_hiding_product_detail() {
if ( ( is_user_logged_in() )
&& has_term( 'login-required', 'product_cat' ) && is_product() ) {
// Add a notice (optional)
wc_add_notice(__("Sorry, but you are not allowed yet to see this product."), 'notice' );
// Shop redirection url
$redirect_url = get_permalink( get_option('woocommerce_shop_page_id') );
wp_redirect($redirect_url); // Redirect to shop
exit(); // Always exit
}
}