Lock Accounts That Haven't Been Used for Months
Blocks logins from accounts that have been inactive for a long time (180 days by default) until they reset their password, which protects forgotten accounts.
Opens WPIDE on
Code
// Days without activity before the account is locked.
$wpide_dormant_days = 180;
// Record activity at most once a day.
add_action( 'init', function () {
$user_id = get_current_user_id();
if ( ! $user_id ) {
return;
}
$last = (int) get_user_meta( $user_id, 'wpide_last_active', true );
if ( time() - $last > DAY_IN_SECONDS ) {
update_user_meta( $user_id, 'wpide_last_active', time() );
}
} );
add_action( 'after_password_reset', function ( $user ) {
update_user_meta( $user->ID, 'wpide_last_active', time() );
} );
add_filter( 'authenticate', function ( $user ) use ( $wpide_dormant_days ) {
if ( ! $user instanceof WP_User || user_can( $user, 'manage_options' ) ) {
return $user;
}
$last = (int) get_user_meta( $user->ID, 'wpide_last_active', true );
if ( ! $last ) {
update_user_meta( $user->ID, 'wpide_last_active', time() );
return $user;
}
if ( time() - $last > $wpide_dormant_days * DAY_IN_SECONDS ) {
return new WP_Error( 'wpide_dormant', sprintf( '<strong>Your account was locked after a long time without use.</strong> Please <a href="%s">reset your password</a> to unlock it.', esc_url( wp_lostpassword_url() ) ) );
}
return $user;
}, 60 );
Notes
Activity is tracked from activation, so existing users get a full period before any lock. Administrators are exempt.
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.