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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.