Halloween Sale 15% off Ends in See the plans
PHP

Use a Custom Page for Logging In

Sends visitors who open wp-login.php to your own login page (for example one with the login form shortcode), and back there when a login fails.

Don’t have WPIDE yet? Install it on your site

Code

// Path of your login page. It must contain a login form, e.g. the [wpide_login_form] shortcode.
$wpide_login_page_path = '/login/';

add_action( 'login_init', function () use ( $wpide_login_page_path ) {
    $action = isset( $_REQUEST['action'] ) ? sanitize_key( $_REQUEST['action'] ) : 'login';
    $method = isset( $_SERVER['REQUEST_METHOD'] ) ? strtoupper( sanitize_key( $_SERVER['REQUEST_METHOD'] ) ) : 'GET';

    // Leave logout, password reset, registration, re-authentication and form posts on wp-login.php.
    if ( 'login' !== $action || 'GET' !== $method || isset( $_GET['interim-login'] ) || isset( $_GET['reauth'] ) || isset( $_GET['loggedout'] ) || isset( $_GET['checkemail'] ) ) {
        return;
    }

    $target = home_url( $wpide_login_page_path );

    if ( ! empty( $_GET['redirect_to'] ) ) {
        $target = add_query_arg( 'redirect_to', rawurlencode( wp_validate_redirect( wp_unslash( $_GET['redirect_to'] ), admin_url() ) ), $target );
    }

    wp_safe_redirect( $target );
    exit;
} );

add_action( 'wp_login_failed', function () use ( $wpide_login_page_path ) {
    $referer = wp_get_referer();

    if ( ! $referer || false === strpos( $referer, $wpide_login_page_path ) || 'wp-login.php' !== ( isset( $GLOBALS['pagenow'] ) ? $GLOBALS['pagenow'] : '' ) ) {
        return;
    }

    wp_safe_redirect( add_query_arg( 'login', 'failed', home_url( $wpide_login_page_path ) ) );
    exit;
} );

Notes

Create the page first and test logging in from a private window before you rely on it.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.