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.
Opens WPIDE on
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
- 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.