How to hide prices for logged out users in WooCommerce

Sometimes, you may want to hide the prices of your products and the “Add to Cart” button from users who are not logged into your WooCommerce store. This can be useful if you want only registered users to see the prices and make purchases. Below, we’ll show you how to achieve this with some PHP code snippets that you can add to your WordPress theme.

 

Hide prices for logged out users

To hide prices for logged out users, add the following code to your theme’s functions.php file:

<?php
add_filter('woocommerce_get_price_html', 'hide_price_for_guests', 10, 2);

function hide_price_for_guests($price, $product) {
    if (!is_user_logged_in()) {
        return '';
    }
    return $price;
}

This code uses the woocommerce_get_price_html filter to check if the user is logged in. If not, the price is set to an empty string, thus hiding the product price.

 

Hide the add to cart button for logged out users

To hide the “Add to Cart” button for logged out users, add the following code to your theme’s functions.php file:

<?php
add_action('woocommerce_single_product_summary', 'hide_add_to_cart_button_for_guests', 1);
add_action('woocommerce_after_shop_loop_item', 'hide_add_to_cart_button_for_guests', 1);

function hide_add_to_cart_button_for_guests() {
    if (!is_user_logged_in()) {
        remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
        remove_action('woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10);
    }
}

This code uses the woocommerce_single_product_summaryand woocommerce_after_shop_loop_itemactions to remove the “Add to Cart” button if the user is not logged in.

Show a message to logged out users

You may want to display a message to logged out users, indicating that they need to log in to see prices and be able to purchase. You can add the following code to display a message:}

<?php
add_action('woocommerce_single_product_summary', 'show_login_message_for_guests', 31);
add_action('woocommerce_after_shop_loop_item', 'show_login_message_for_guests', 11);

function show_login_message_for_guests() {
    if (!is_user_logged_in()) {
        echo '<p class="login-to-see-prices">Please, <a href="' . wp_login_url(get_permalink()) . '">log in</a> to see prices and purchase.</p>';
    }
}

This code adds a message right after the “Add to Cart” buttons were removed, inviting users to log in.

 

With these simple PHP code snippets, you can hide prices and the “Add to Cart” button from users who are not logged into your WooCommerce store. This can help you better control who can see your prices and make purchases on your site. If you have any questions or need further assistance, feel free to leave a comment or contact us.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to Top
0
Would love your thoughts, please comment.x
()
x