WordPress redirection after login fails


If you create your own login form or use the wordpress wp_login_form function to create one, you have the option to redirect user to certain pages after login by including a “redirect_to” variable upon submission. If it doesn’t work, it means that you have certain plugins that hook on to the wp_login action. Commercial plugins are hard to debug because the code is encrypted. One way around this is to intercept the wp_login earlier than other plugin, perhaps using a higher priority. Eg

add_action( 'wp_login', 'my_login_redirect', 2, 2 );
function my_login_redirect( $login, $user ) {
  // $login is the username 
  // $user is the WP_USER object

   // don't redirect the wp-login.php. else you get infinite loop
   if ($_SERVER['REQUEST_URI'] != '/wp-login.php') {
     // if you are using the wp_login_form function, you can get the $_POST['redirect_to'] variable and redirect user to the right place.
     // allows get as well.
     if (isset($_REQUEST['redirect_to'])) {
        $referrer = $_REQUEST['redirect_to'];
     }
     else {
       // redirect to the referrer page
       $referrer = $_SERVER['HTTP_REFERER'];
     }
    wp_safe_redirect($referrer); 
    exit;
  }
}
Like it.? Share it:
Tags:

Comments are closed.