WordPress login widget redirect prevention

WordPress Login Pod

I don’t know if I’ve mentioned this before, but WordPress has become my favourite open source tool ever. There is very little that you can’t do with it. I like how you can hook into almost any core WordPress functionality and last night I had to modify the??wordpress login widget.

The problem I solved was preventing wordpress to redirect to wp-login.php after you’ve attempted to login using the wordpress login widget. For example, if you have a login widget in your sidebar and type in incorrect account details and hit submit – WordPress then redirects you to it’s standard login page wp-login.php. I thought, what’s the point of having the widget if you end up getting redirected to another page when you type in your credentials incorrectly. The beauty of WordPress is that you can hook into and customise almost any core functionality using WordPress hooks and filters.

So here are a couple of hooks that will prevent WordPress from redirecting to the default login page if you put in incorrect credentials in your login widget. The first one redirects back to referrer page if credentials are incorrect, the second one redirects to referrer if you leave either username or password blank.

/*-------------------------------------------------------------------------------------*/
/* Login Hooks and Filters
/*-------------------------------------------------------------------------------------*/
if( ! function_exists( 'custom_login_fail' ) ) {
    function custom_login_fail( $username ) {
        $referrer = $_SERVER['HTTP_REFERER']; // where did the post submission come from?
        // if there's a valid referrer, and it's not the default log-in screen
        if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {
            if ( !strstr($referrer,'?login=failed') ) { // make sure we don?t append twice
                wp_redirect( $referrer . '?login=failed' ); // append some information (login=failed) to the URL for the theme to use
            } else {
                wp_redirect( $referrer );
            }
            exit;
        }
    }
}
add_action( 'wp_login_failed', 'custom_login_fail' ); // hook failed login
if( ! function_exists( 'custom_login_empty' ) ) {
    function custom_login_empty(){
        $referrer = $_SERVER['HTTP_REFERER'];
        if ( strstr($referrer,'mylogin') && $user==null ) { // mylogin is the name of the loginpage.
            if ( !strstr($referrer,'?login=empty') ) { // prevent appending twice
                wp_redirect( $referrer . '?login=empty' );
            } else {
                wp_redirect( $referrer );
            }
        }
    }
}
add_action( 'authenticate', 'custom_login_empty');

Thanks to WP insite for the tip!

Marko