7

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!

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

4 Answers 4

12

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.

12
  • 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. Nov 27, 2014 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, 2014 at 13:28
  • Okay, where does the redirect() happen? Nov 27, 2014 at 13:30
  • The wp_redirect() is pluggable but you can also access the wp_redirect filter.
    – birgire
    Nov 27, 2014 at 13:33
  • 1
    ok thanks, it looks like you found a Javascript solution that works for you over there.
    – birgire
    Nov 27, 2014 at 16:37
3

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 ) ) );
5
  • The project died an year ago. Well, what's the point of answering now? Coz did you even read the previous accepted answer? Dec 1, 2015 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, 2015 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. Dec 1, 2015 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, 2015 at 7:28
  • 1
    Ha ha... Fine. I give up. You are right! :) Dec 1, 2015 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.

3
  • 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. Jul 6, 2016 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, 2016 at 10:30
  • Kindly I would like to check the question's solution in StackOverflow... Jul 6, 2016 at 10:46
0

I know it's late, but I am posting the solution so that it can help someone in need at the moment.

This is what I am doing and it is working perfectly.

function redirect_user_tologin(){
  global $post;
  $post_slug = $post->post_name;

  if(!is_user_logged_in()){
      if($post_slug == 'my-account') { //can add multiple conditions

          //create dynamic redirect page link
          $redirect = urlencode(site_url().'/'.$post_slug);

          //redirection
          wp_safe_redirect(site_url().'/wp-login.php/?redirect_to=' .$redirect);
          exit;
       }
   }
}
add_action('wp', 'redirect_to_login');

Explanation

If user is not logged in than wp_safe_redirect will take user to login page.

In order to redirect user after login, we will pass page link as value in redirect_to parameter so that it will take user to that particular page.

Login page url: site_url().'/wp-login.php/

Redirect page link: redirect_to=' .$redirect

1

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.