11

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?

23

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.

  • Thank you for your help. The file functions.php is in my theme folder?? And how can i recall this function from the product page? Thanks :-) – Alessandro Jan 29 '14 at 8:30
  • Thank you very much. Your code works fine for me. Many many thanks :) – Alessandro Jan 29 '14 at 9:45
  • Make sure you don't set any of the woocommerce pages as your homepage, because then site won't work anymore. – SPRBRN Nov 13 '17 at 9:23
7

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.

  • 1
    This is not the best method to redirect to the My Account page. It is better to retrieve the permalink of the My Account page that you linked in your WooCommerce settings. This way whenever the permalink is changed or you have a multi-language site running the permalink will still be correctly retrieved. In short: It's better not to hardcode permalinks/slugs (or URL's in general). A better method would be: wp_redirect( get_permalink( get_option( 'woocommerce_myaccount_page_id' ) ) ); – Rens Tillmann Mar 2 '18 at 19:25
  • you code missing ; it end – user889030 Feb 6 at 18:52

protected by Community Mar 28 '16 at 20:07

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.