WooCommerce: Show or hide product category if user is logged inn.

Show a product category if user is logged in and another product category if user is not logged in.

A default shop page with a few products using the theme Twenty Twenty Two.
There are three categories in use. “Uncategorized” (first product), “Rocks” (second product) and “Books” (third and fourth product).

Shop page WooCommerce WordPress
Shop page WooCommerce.

I will split up the categories so that “Uncategorized” and “Rocks” are seen for not logged in users. While “Books” seen for logged in users.

/* Show/Hide product category if user logged in/out.
https://businessbloomer.com/woocommerce-remove-specific-category-shop-loop/
https://stackoverflow.com/questions/34684881/hide-products-from-users-who-are-not-logged-in-using-tags/34689768#34689768 */

add_action( 'woocommerce_product_query', 'show_hide_products_category_shop' );
function show_hide_products_category_shop( $q ) {
    $tax_query = (array) $q->get( 'tax_query' );

    if ( is_user_logged_in() ) {
	// If user not logged in show categories Uncategorized and Rocks.
        $tax_query[] = array(
               'taxonomy' => 'product_cat',
               'field' => 'slug',
               'terms' => array( 'Uncategorized', 'Rocks' ), // Category slug here
               'operator' => 'NOT IN'
        );

    } else {
	// If user logged in show category Books.
        $tax_query[] = array(
               'taxonomy' => 'product_cat',
               'field' => 'slug',
               'terms' => array( 'Books' ), // Category slug here
               'operator' => 'NOT IN'
        );
    }
		
    $q->set( 'tax_query', $tax_query );

}

Any product category not mentioned in user logged in/out code will be seen in both.

Resources:

https://businessbloomer.com/woocommerce-remove-specific-category-shop-loop/

https://stackoverflow.com/questions/34684881/hide-products-from-users-who-are-not-logged-in-using-tags/34689768#34689768

https://businessbloomer.com/woocommerce-hide-price-add-cart-logged-users/

Share the article:

Leave a Reply

Your email address will not be published. Required fields are marked *