Halloween Sale 15% off Ends in See the plans
PHP

Protect wp-login.php With a Secret Key

Hides the login page behind a secret link: wp-login.php returns "Not Found" unless you have opened it with your key once in this browser.

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

Code

// Open https://your-site.com/wp-login.php?access=YOUR-SECRET once per browser (remembered for 30 days).
$wpide_login_key_param = 'access';
$wpide_login_key       = 'change-this-to-a-long-random-secret';

add_action( 'login_init', function () use ( $wpide_login_key_param, $wpide_login_key ) {
    $action = isset( $_REQUEST['action'] ) ? sanitize_key( $_REQUEST['action'] ) : 'login';

    // Logout, password-protected posts and password reset links from emails always work.
    if ( is_user_logged_in() || in_array( $action, array( 'logout', 'postpass', 'rp', 'resetpass', 'confirmaction' ), true ) ) {
        return;
    }

    $cookie   = 'wpide_login_access';
    $expected = hash_hmac( 'sha256', $wpide_login_key, wp_salt( 'auth' ) );

    if ( isset( $_GET[ $wpide_login_key_param ] ) && hash_equals( $wpide_login_key, (string) wp_unslash( $_GET[ $wpide_login_key_param ] ) ) ) {
        setcookie( $cookie, $expected, time() + 30 * DAY_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
        return;
    }

    if ( isset( $_COOKIE[ $cookie ] ) && hash_equals( $expected, (string) wp_unslash( $_COOKIE[ $cookie ] ) ) ) {
        return;
    }

    status_header( 404 );
    nocache_headers();
    header( 'Content-Type: text/html; charset=utf-8' );
    echo '<!DOCTYPE html><html><head><title>404 Not Found</title><meta name="robots" content="noindex"></head><body><h1>Not Found</h1></body></html>';
    exit;
} );

Notes

Bookmark the secret link, and if you lose it turn the snippet off from WPIDE safe mode.

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.