18

I have a function that redirects users to the login page (home) if they're trying to access any other page without being logged in, here's how it works:

function restrict_access_if_logged_out(){
    if (!is_user_logged_in() && !is_home()){
        wp_redirect( get_option('home') );
    }
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );

Really simple and works fine, the problem is that is that I need to redirect them to the url they were trying to go to after they successfully log in, exactly like the WordPress backend works.

Is there a way to do this? Thanks in advance!

7 Answers 7

16

You can do that easily. You just need to specify a redirection parameter. If you are using a login link on the homepage to go to the login page, then @sisir's solution is correct.

<?php echo wp_login_url( $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"] ); ?>

If you are using a custom form on the frontpage, then inside the <form>, make sure you fill in a hidden field with the url to redirect

<input type="hidden" name="redirect_to" value="<?php echo $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; ?>" />

And if you are using wp_login_form() to generate the form, then fill in a parameter - http://codex.wordpress.org/Function_Reference/wp_login_form

<?php
$args = array(
        'echo' => true,
        'redirect' => site_url( $_SERVER['REQUEST_URI'] ), 
        'form_id' => 'loginform',
        'label_username' => __( 'Username' ),
        'label_password' => __( 'Password' ),
        'label_remember' => __( 'Remember Me' ),
        'label_log_in' => __( 'Log In' ),
        'id_username' => 'user_login',
        'id_password' => 'user_pass',
        'id_remember' => 'rememberme',
        'id_submit' => 'wp-submit',
        'remember' => true,
        'value_username' => NULL,
        'value_remember' => false );

wp_login_form( $args );
?>

Change other parameters as per what you have or need.

2
  • i am using custom form, and i am using your provided hidden field solution, but in my case i am being redirected to url like this 'localhost/wordpress/localhost/wordpress/blog/someone'. any help?
    – rafi
    Feb 6, 2014 at 6:15
  • i have got this, i am using double slash. so my solution is like this <?php echo '//' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]; ?>
    – rafi
    Feb 6, 2014 at 6:19
7

Try passing the_permalink() as the $redirect argument:

function restrict_access_if_logged_out(){
    if (!is_user_logged_in() && !is_home()){
        wp_redirect( the_permalink() );
    }
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );

EDIT:

Sorry, misunderstood your question originally. Try this:

function restrict_access_if_logged_out(){
    if (!is_user_logged_in() && !is_home()){
        $redirect = home_url() . '/wp-login.php?redirect_to=' . urlencode( $_SERVER['REQUEST_URI'] );
        wp_redirect( $redirect );
        exit;
    }
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );

Note also: proper usage of wp_redirect() generally requires adding exit;, which I have added to my second example.

2
  • That doesn't make any sense, the redirect needs to go to home, that's working fine I need some way to catch the original url and redirect the user there once he logs in. Apr 30, 2011 at 5:12
  • Sorry, misunderstood your question originally. I've added an edit that hopefully addresses your use case. Apr 30, 2011 at 12:34
5

Thanks all, I kind of used a bit of what everyone recommended so in the end my code looks like this:

function restrict_access_if_logged_out(){
    if (!is_user_logged_in() && !is_home()){
        wp_redirect( get_option('home') . '?redirect_to=' . esc_url($_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]) );
    }
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );

And on my login form (I'm hardcoding my login form in my aplication thanks @Ashfame for letting me know about wp_login_form I had no idea it existed) I added this when user credentials are fine and they're ready to login:

if (isset($_REQUEST['redirect_to'])){
    wp_redirect($_REQUEST['redirect_to']);
    // wp_redirect() does not exit automatically, and should almost always be followed by a call to exit;
    exit;

} else {
    wp_redirect(get_bloginfo('url') . '/groups/');
    exit;
}

Thanks a lot for your help, I voted up everyone!

3
  • Hi Javier, in which file did you add these functions? Thanks. Aug 24, 2012 at 10:09
  • In functions.php Aug 25, 2012 at 20:40
  • 4
    You should call exit() or die() after wp_redirect(). Otherwise it's possible that code after wp_redirect() will execute, which can lead to bugs and security vulnerabilities.
    – Ian Dunn
    Nov 6, 2012 at 17:21
2

this is my code that i use people to direct to wp login page. Then when logged in they returned back to where they were. But it is not home page but the wordpress login page where i setup custom login.

<?php echo wp_login_url( $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]) ?>

You might wanna research with. Typically you will get the current url of a user by $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]

1

I know this is super late, but I made a post about exactly how to do this if any future people find this and need it:

http://www.ryanprejean.com/force-login-with-redirect-and-exceptions/

3
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. See How to Answer.
    – Gabriel
    Mar 17, 2016 at 21:37
  • 1
    Link is broken (April 2020). Apr 22, 2020 at 13:01
  • I was able to access the broken link with the Wayback machine, in case anyone else needs the info.
    – jsmod
    Oct 26, 2020 at 12:13
0

The login_redirect filter hook is a more complete and effective solution here. This way, you can offer different redirect paths for different levels of users, or maintain the redirect URL in the case of an error when logging in (i.e. Incorrect Password).

function login_redirect( $redirect_to, $request, $user ){
  if(isset($_REQUEST['redirect_to'])){
    return $_REQUEST['redirect_to'];
  }
  return admin_url();
}
add_filter( 'login_redirect', 'login_redirect', 10, 3 );

function restrict_access_if_logged_out(){
  if (!is_user_logged_in() && !is_home()){
    $redirect = home_url() . '?redirect_to=' . esc_url($_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
    wp_redirect( $redirect );
  }
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );
0

It has not worked any of your answers but only adding a little thing, it worked! Here my code:

function login_redirect( $redirect_to, $request, $user ){
  if(isset($_REQUEST['redirect_to'])){
    return $_REQUEST['redirect_to'];
  }
  return admin_url();
}
add_filter( 'login_redirect', 'login_redirect', 10, 3 );

function restrict_access_if_logged_out(){
  if (!is_user_logged_in() && !is_home()){
    $redirect = home_url() . '/wp-login.php?redirect_to=' . esc_url($_SERVER["HTTP_HOST"] . urlencode($_SERVER["REQUEST_URI"]));
    wp_redirect( $redirect );
    exit;
  }
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );

Only I added /wp-login.php in comparison to @Matt's response, but for me has been the key. Hope that helps! :)

**EDIT:

I detected an ERROR when you are FORCE wordpress to navegate in HTTPS. This method doesn't work because the redirection is in HTTP. For fix the problem I changed the function. This is the result:

function restrict_access_if_logged_out(){
  global $wp;
  $protocol='http';
  if (isset($_SERVER['HTTPS']))
    if (strtoupper($_SERVER['HTTPS'])=='ON')
      $protocol='https';
  if (!is_user_logged_in() && !is_home() && ($wp->query_vars['pagename'] != 'downloads') ){
    $redirect = home_url() . "/wp-login.php?redirect_to= $protocol://" . $_SERVER["HTTP_HOST"] . urlencode($_SERVER["REQUEST_URI"]);
    wp_redirect( $redirect );
    exit;
  }
}
add_action( 'wp', 'restrict_access_if_logged_out', 3 );

I check the protocol and then I deleted 'esc_url' and added the correct protocol: $protocol://. Also I changed the "".

I'm based with this page.

Your Answer

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

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