The question:
I have a website using WordPress, and an e-commerce using WooCommerce. I would like my shop (and all its pages) to be seen by logged in users only.
Via the User Access Manager plugin, I have denied access to the shop page, but with a direct link to a product etc. one can access that particular page nonetheless, even if the user is not logged in.
How can I redirect users, who are not logged in, to another page if they try to access a WooCommerce page?
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
Put this in your functions.php
file:
function wpse_131562_redirect() {
if (
! is_user_logged_in()
&& (is_woocommerce() || is_cart() || is_checkout())
) {
// feel free to customize the following line to suit your needs
wp_redirect(home_url());
exit;
}
}
add_action('template_redirect', 'wpse_131562_redirect');
What does it do?
We check if a not-logged-in user wants to see a WooCommerce page, and redirect him/her to our home page.
Method 2
I just changed the redirection to
wp_redirect( site_url('my-account/') )
so users are redirected on the “My-Account” page if not logged in or registered.
Method 3
I would change to this
wp_safe_redirect( wc_get_page_permalink( 'myaccount' ) );
instead of
wp_redirect( site_url('my-account/') );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0