I am developing a WP site locally and I want the content to be viewable only to users that have logged in, except for the front page that's visible to everyone.

When a non-logged in user clicks on a link from the front page, it takes him to a customized login page made with Theme My Login. If he logins succesfuly from there, I want him taken to the page he initially requested, i.e. the link he clicked while at the front page.

I have the first part of this working. Non-logged in users are taken to the custom login page. I cannot find a way to send them directly where they wanted to go, though. I have read several things and posts on the matter, tried different plugins, but haven't managed to apply them to my case.

This is the code I am using to send them to the login page:

function checkLogged()
    $pg = get_permalink();
    if (!is_user_logged_in() && !is_front_page() && $pg != home_url('/?page_id=126'))
add_action('wp_head', 'checkLogged');
where the page with ID=126 is the custom login page.

Right now I am redirecting to the front page after login. But I want to change that to the requested page. I am using the login_redirect filter for that.

function takeMeThere()
    $lastPage = wp_get_referer();
    $loginPage = home_url('/?page_id=126');
    if ($lastPage == $loginPage)
        wp_redirect(home_url()); //this redirection should be to the requested page
add_filter('login_redirect', 'takeMeThere', 10, 3);

I don't know if some of the code in the latter function is redundant but the login page kind of breaks without that (the footer doesn't appear). Anyway, essentially I'm asking how I can somehow retrieve the url of the link the user clicked on when not logged in. Or if there's an alternative approach I'd be happy to try it but I want that custom login page, not the Wordpress one.

Any help would be greatly appreciated.

1 Answer 1


Adding this snippet to the functions.php of your wordpress theme will redirect visitors to the page they were viewing after logging in.

  if ( (isset($_GET['action']) && $_GET['action'] != 'logout') || (isset($_POST['login_location']) && !empty($_POST['login_location'])) ) {
            function my_login_redirect() {
               $location = $_SERVER['HTTP_REFERER'];
            add_filter('login_redirect', 'my_login_redirect', 10, 3);
  • Thanks for the response, however this snippet takes me back to the login page (technically the last page viewed before logging in) which has now become a log out page with links to Dashboard, Profile etc. What I want is for them to go to the page they asked to be taken to before being redirected to the login page.
    – parantox
    Commented Jun 29, 2012 at 9:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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