# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Login](https://wpide.com/library/category/login/)
- Tags: login, security, inactive
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/block-dormant-accounts/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Lock Accounts That Haven't Been Used for Months" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
