Halloween Sale 15% off Ends in See the plans
PHP

Expire Passwords After 90 Days

Makes users in chosen roles reset their password once it is older than 90 days; at login they are told it has expired and pointed to the password reset form.

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

Code

// Roles whose passwords expire, and after how many days.
$wpide_expiring_roles  = array( 'administrator', 'editor', 'shop_manager' );
$wpide_password_days   = 90;

$wpide_mark_password_changed = function ( $user_id ) {
    update_user_meta( $user_id, 'wpide_password_changed', time() );
};

add_action( 'user_register', $wpide_mark_password_changed );
add_action( 'after_password_reset', function ( $user ) use ( $wpide_mark_password_changed ) {
    $wpide_mark_password_changed( $user->ID );
} );
add_action( 'profile_update', function ( $user_id, $old_user ) use ( $wpide_mark_password_changed ) {
    $user = get_userdata( $user_id );

    if ( $old_user instanceof WP_User && $user && $user->user_pass !== $old_user->user_pass ) {
        $wpide_mark_password_changed( $user_id );
    }
}, 10, 2 );

add_filter( 'authenticate', function ( $user ) use ( $wpide_expiring_roles, $wpide_password_days, $wpide_mark_password_changed ) {
    if ( ! $user instanceof WP_User || ! array_intersect( $wpide_expiring_roles, (array) $user->roles ) ) {
        return $user;
    }

    $changed = (int) get_user_meta( $user->ID, 'wpide_password_changed', true );

    if ( ! $changed ) {
        $wpide_mark_password_changed( $user->ID );
        return $user;
    }

    if ( time() - $changed > $wpide_password_days * DAY_IN_SECONDS ) {
        return new WP_Error(
            'wpide_password_expired',
            sprintf( '<strong>Your password has expired.</strong> Please <a href="%s">set a new password</a> to continue.', esc_url( wp_lostpassword_url() ) )
        );
    }

    return $user;
}, 60 );

Notes

The clock starts for everyone on the day you activate the snippet, so nobody is locked out straight away.

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.