Hide Price & Add to Cart for Non Logged in Users for Specific Products

This WordPress WooCommerce code snippet is designed to hide the price and “Add to Cart” button for specific products for non-logged-in users. This is particularly useful for online stores that want to display prices only to registered users or to offer exclusive products to certain users.

The code consists of three main parts. The first part is a function that checks if the current product is in the list of products that should be hidden for non-logged-in users. The second part alters the “is_purchasable” status of the product for non-logged-in users, rendering it unpurchasable for them. The third part hides the price and “Add to Cart” button for these specific products, displaying a message that prompts users to log in to see prices. The changes apply on both single product pages and the shop loop.

Before using this code, you should replace the product IDs in the $not_purchasable_products array with the IDs of the products you want to hide from non-logged-in users.

PHP
/**
 * Hide Price & Add to Cart for Non Logged in Users for Specific Products
 */
function is_non_purchasable_products_for_visitors( $product ) {
    $not_purchasable_products = array( 23, 22 ); // Replace with Products ID you want to set as non purchasable items for non logged in user
    if ( ! is_user_logged_in() && ( in_array( $product->get_id(), $not_purchasable_products ) ) ) { 
        return true;
    } else {
        return false;
    }
}
function wws_set_not_purchasable_not_logged_in( $is_purchasable, $product ) {
    if ( is_non_purchasable_products_for_visitors( $product ) ) { 
        $is_purchasable = false;
    }
    return $is_purchasable;
}
function wws_hide_price_not_logged_in( $price_html, $product ) {
    if ( is_non_purchasable_products_for_visitors( $product ) ) { 
        $price_html = '<div><a href="' . get_permalink( wc_get_page_id( 'myaccount' ) ) . '">' . __( 'Login with wholesale account to see prices', 'wws' ) . '</a></div>';
    }
    return $price_html;
}
function wws_hide_addcart_not_logged_in( $add_to_cart, $product, $args ) {
    if ( is_non_purchasable_products_for_visitors( $product ) ) { 
        $add_to_cart = '';
    }
    return $add_to_cart;
}
add_filter( 'woocommerce_is_purchasable', 'wws_set_not_purchasable_not_logged_in', 10, 2 );
add_filter( 'woocommerce_get_price_html', 'wws_hide_price_not_logged_in', 10, 2 );
add_filter( 'woocommerce_loop_add_to_cart_link', 'wws_hide_addcart_not_logged_in', 10, 3 );