Force Visitors to Login Before Accessing WooCommerce Shop

Support
Topic WordPress, Security
Access FTP
public_html/wp-content/themes/theme/functions.php

The Simplest Way to Prevent Random Visitors From Accessing Your Store Without Using a Plugin

Sometimes WooCommerce shop owners want to restrict non-logged in users from accessing the shop. There are a number of reasons this might be useful, such as a shop geared towards wholesaling or a shop selling specific products or services to a group of clients or customers. For example, Stackpilot provides some development services to agencies and has turned WooCommerce into a wholesale pricing catalog for everything from WordPress websites to configuring 3rd party applications like Zendesk or Intercom for their clients. This system is separate from our hosting billing system because it’s geared towards agencies who are ultimately invoiced for the work and pay lower than retail rates for the services.

To prevent visitors who aren’t logged in from browsing your shop you’ll want simply add the following code to your functions.php file. In doing so, any logged out user attempting to access any WooCommerce page will be re-directed to my-account which, when logged out, will prompt the user to login. Once they login they’re free to use your shop!

function woo_login_redirect() {
if (
! is_user_logged_in()
&& (is_woocommerce() || is_cart() || is_checkout())
) {
wp_redirect( '/my-account/' );
exit;
}
}
add_action('template_redirect', 'woo_login_redirect');

This is pretty straightforward easy to implement. As always, if you’re using a commercial theme make sure you’ve setup a proper child theme and add this to the functions.php file in the child theme folder to prevent accidentally overwriting this during a theme update!

4
Questions or Comments

avatar
2 Comment threads
2 Thread replies
1 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
Craig MarolfSomnath Jadhavaaron Recent comment authors
  Subscribe  
Notify of
aaron
Guest

Hi, in the code above, do you mean to have the “&&” or should that just be “&&” for the code?

Somnath Jadhav
Guest

Hello,
Thanks for writing post.
I want to user to be login in to view product details. Is there any plugin / code snippet.
Let me know.

Thanks

Login
Resources
Contact

Quick Open Ticket

You can quickly open a ticket without logging in. Be sure to use your login email address and include the web address of your service.