6

I am not using any custom login plugins or any bespoke code. A few of my pages have got this bit of code in them at the very beginning.

<?php
    if(!is_user_logged_in())
        wp_redirect('/login/');
?>

So, this doesn't allow the users to view the page when not logged in. I have these pages bearing this bit of code:

/wp-content/my-theme/my-account/
/wp-content/my-theme/my-account/world.php
/wp-content/my-theme/my-account/subscription.php
/wp-content/my-theme/my-dashboard.php
/wp-content/my-theme/my-files.php

Now, when a user goes to any of the above pages, without logging in, it redirects to the login page, and when the user logs in, it lands them to the my-account/ page.

I want to change the current scenario to make the user redirect to the referring page, where he came from. I tried the following things, which never worked.

Using a HTTP_REFERRER

In the login/ form, I placed this bit of code:

<input type="hidden" name="redirect" value="<?php echo $_SERVER['HTTP_REFERER']; ?>" />

Hacking functions.php

In the functions.php, I placed this bit of code:

if ( (isset($_GET['action']) && $_GET['action'] != 'logout') || (isset($_POST['login_location']) && !empty($_POST['login_location'])) ) {
        add_filter('login_redirect', 'my_login_redirect', 10, 3);
        function my_login_redirect() {
                $location = $_SERVER['HTTP_REFERER'];
                wp_safe_redirect($location);
                exit();
        }
}

References:


I have also tried these and failed:

Nothing was working out. I am happy to provide further details if needed. Thanks in advance. :)


Update

I have modified the code this way:

<?php
    if(!is_user_logged_in())
        wp_redirect('/login/?redirect_to=' . $_SERVER["REQUEST_URI"]);
?>

This renders the login page this way:

/login.php?redirect_to=/my-account/subscription.php

This would be enough for me to authenticate and redirect. But I need to find the bit where the real redirection happens and I want to redirect it using the redirect_to parameter!

  • Did you ever find a solution to this problem? I am having the same issue! – Tom Nolan Jun 7 '15 at 16:31
  • @ThomasNolan Actually I used a temporary variable! ;) – Praveen Kumar Purushothaman Jun 8 '15 at 4:46
8

I'm not sure I understand your setup, but here are few ideas:

A) Display a login link with the redirect_to parameter set:

You could add the following to your custom template pages:

if( ! is_user_logged_in() )
{
    printf( '<a href="%s">%s</a>', 
        wp_login_url( get_permalink() ),
        __( 'You need to login to view this page!' )
    );
}

This will generate a login link, for anonymous visitors, with the current page in the redirect_to GET parameter.

B) Redirect to the wp-login.php with the redirect_to parameter set:

Notice that the call to wp_redirect() must happen before the HTTP headers are sent.

We can call it within the template_redirect hook:

add_action( 'template_redirect', 
    function()
    {
        if( ! is_user_logged_in() 
            && is_page( array( 'member-page-1', 'member-page-2' ) ) 
        )
        {
            wp_safe_redirect( wp_login_url( get_permalink() ) ); 
            exit();
        }
    }
);

where we restrict the access to pages with the slugs member-page-1 and member-page-2.

C) The native login form (in-line):

Another option would be to include the native login form, directly into the page content:

add_filter( 'the_content', function( $content ) {

    if( ! is_user_logged_in() 
        && is_page( array( 'member-page-1', 'member-page-2' ) ) 
    )
        $content = wp_login_form( array( 'echo' => 0 ) );

    return $content;
}, PHP_INT_MAX );

where we restrict the access to pages with the slugs member-page-1 and member-page-2.

Notice you would have to take care of the archive/index/search pages.

Update: I simplified it by using the wp_login_url() function.

  • I already give the redirect_to to the login.php. Check the updated answer. But post logging in, it just goes to my-account, which has to be replaced with redirect_to. – Praveen Kumar Purushothaman Nov 27 '14 at 13:21
  • Notice that you must use wp_redirect before the HTTP headers are sent. You might want to use the template_redirect action, for example. – birgire Nov 27 '14 at 13:28
  • Okay, where does the redirect() happen? – Praveen Kumar Purushothaman Nov 27 '14 at 13:30
  • The wp_redirect() is pluggable but you can also access the wp_redirect filter. – birgire Nov 27 '14 at 13:33
  • 1
    ok thanks, it looks like you found a Javascript solution that works for you over there. – birgire Nov 27 '14 at 16:37
2

Usgin get_permalink(), as suggested in the accepted answer, will work only if you are in a post (of any type) but it won't work, for example, if you are in a category archive. To make it work anywhere, the current URL is needed, not matter what type of content we are seeing.

To get the current URL in WordPress we can get the current request from the global $wp object and append it to the site url using add_query_arg(). We can use the result in the redirect_to parameter of wp_login_url() function:

wp_login_url( site_url( add_query_arg( array(), $wp->request ) ) );

The same approach can be used with wp_logout_url() if needed:

wp_logout_url( site_url( add_query_arg( array(), $wp->request ) ) );
  • The project died an year ago. Well, what's the point of answering now? Coz did you even read the previous accepted answer? – Praveen Kumar Purushothaman Dec 1 '15 at 7:13
  • Yes, I read the previous answer and I think I could give a better answer, maybe not for you but for others. Note that this site (and any of the StackExchange sites in general) is used as reference by thousands of people and they can get outdated answers; that is why giving new answers or updating old answers is always very wellcome. Remember taht the help you get here is not only for you. – cybmeta Dec 1 '15 at 7:20
  • 1
    Ha ha... Man, I hold 62k in StackOverflow. I understand what you mean. That's a custom code gone wrong, and I am not sure it will help? Will it? If so, Thank you so much. – Praveen Kumar Purushothaman Dec 1 '15 at 7:21
  • 1
    I have no doubt that it can help. For example, this other question has been marked a few minutes ago as duplicated of the one we are discussing. – cybmeta Dec 1 '15 at 7:28
  • 1
    Ha ha... Fine. I give up. You are right! :) – Praveen Kumar Purushothaman Dec 1 '15 at 7:29
0

You can also use this code in your custom login page

if ( ! is_user_logged_in() ) { // Display WordPress login form:
   $args = array(
    'redirect' => esc_url($_SERVER['HTTP_REFERER']), 
    'form_id' => 'loginform-custom',
    'label_username' => __( 'Email' ),
    'label_password' => __( 'Password' ),
    'label_log_in' => __( 'Log In' ),
    'remember' => false
);
wp_login_form($args);
echo '<p><a href="' . wp_lostpassword_url($redirect) .'">Lost Password</a></p>';
}

This will redirect the user to referrer page, after login.

  • 1
    This was posted as an answer, but it does not attempt to answer the question. It should possibly be an edit, a comment, another question, or deleted altogether. – Praveen Kumar Purushothaman Jul 6 '16 at 8:13
  • This does answer the question. You can see that the user is redirected to custom login page <?php if(!is_user_logged_in()) wp_redirect('/login/'); ?> – KKumar Jul 6 '16 at 10:30
  • Kindly I would like to check the question's solution in StackOverflow... – Praveen Kumar Purushothaman Jul 6 '16 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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