3

I created some custom login/registration template pages and now I want that every request to wp-login.php to be redirected to a custom url. Now I have something like this:

add_action('init','possibly_redirect');
 function possibly_redirect(){
global $pagenow;
if( '/wp-login.php' == $pagenow ) {
wp_redirect('/login');
exit();
}
}

but it doesn't work properly because when I click a logout link (in a meta widget) it will redirect me to the /login link and not doing logout. Do you have other method to do this in a safe or a better way ? Thank you.

1
  • 1
    Add if ( isset( $_GET['action'] ) && $_GET['action'] == 'logout' ) return; for example.
    – soulseekah
    Apr 2, 2012 at 11:50

4 Answers 4

7

To restrict direct access only for 'wp-login.php', without POST or GET request (useful for custom ajax login forms), I use the advanced function:

function possibly_redirect(){
  global $pagenow;
  if( 'wp-login.php' == $pagenow ) {
    if ( isset( $_POST['wp-submit'] ) ||   // in case of LOGIN
      ( isset($_GET['action']) && $_GET['action']=='logout') ||   // in case of LOGOUT
      ( isset($_GET['checkemail']) && $_GET['checkemail']=='confirm') ||   // in case of LOST PASSWORD
      ( isset($_GET['checkemail']) && $_GET['checkemail']=='registered') ) return;    // in case of REGISTER
    else wp_redirect( home_url() ); // or wp_redirect(home_url('/login'));
    exit();
  }
}
add_action('init','possibly_redirect');
4

Actually I found the right way to do this.

For redirect wordpress login to a custom url:

function redirect_login()
{
wp_redirect( home_url( '/login' ) );
exit(); 
}
add_action( 'login_form_login', 'redirect_login' );

For redirect wordpress registration to a custom url:

 function redirect_register()
{
wp_redirect( home_url( '/registration' ) );
exit(); 
}
add_action( 'login_form_register', 'redirect_register' );

I think the code is very simple to understand, basically you add hooks for login and register url's and then use wp-redirect to redirect to a custom url. All requests to wp-login.php and wp-login.php?action=register will be redirected to the custom url's you set.

1

I would recommend John's answer, having exit() omitted. So, the code that is fully functional in my case is:

function redirect_login() {
    wp_redirect( home_url( '/login' ) ); 
}
add_action( 'login_form_login', 'redirect_login' );

It seems that the exit() is making it impossible for a user to login.

0

Two things to note from the WP function reference for wp_redirect()...

  1. an exit; is indeed part of the usage, and
  2. $location parameter is to be the "Absolute URI", one including the protocol (http://) Example of Absolute/Full URI: http://www.example.com/blog/images/icecream.jpg

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.