Redirect if current user is logged out and current page is /my-account

I need my woocommerce site to do the following. If the user visits the /my-account page but is logged out I need it to redirect to the /login page. I currently have half of it (if is logged out) but I need to test if it’s the my-account/ page as well which I can’t figure out. Any help would be really appreciated!

if ( !is_user_logged_in()) {
    wp_redirect( '/login' );
    die();
}

1 Answer
1

Fixed!

I had to use the wp hook which means that the redirect function is only run once the whole page is loaded! Sweet 🙂

add_action( 'wp', 'redirect' );
function redirect() {
  if ( is_page('my-account') && !is_user_logged_in() ) {
      wp_redirect( home_url('/login') );
      die();
  }
}

Leave a Comment