Make New Users Change Their Password on First Login
When an administrator creates an account, the new user is sent to their profile and asked to choose a new password before they can use the rest of the site.
Opens WPIDE on
Code
add_action( 'user_register', function ( $user_id ) {
if ( is_admin() && current_user_can( 'create_users' ) ) {
update_user_meta( $user_id, 'wpide_must_change_password', 1 );
}
} );
// Changing the password from the profile screen or the reset form clears the flag.
add_action( 'profile_update', function ( $user_id, $old_user ) {
$user = get_userdata( $user_id );
if ( $old_user instanceof WP_User && $user && $user->user_pass !== $old_user->user_pass ) {
delete_user_meta( $user_id, 'wpide_must_change_password' );
}
}, 10, 2 );
add_action( 'after_password_reset', function ( $user ) {
delete_user_meta( $user->ID, 'wpide_must_change_password' );
} );
$wpide_needs_new_password = function () {
if ( ! is_user_logged_in() || wp_doing_ajax() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
return false;
}
return (bool) get_user_meta( get_current_user_id(), 'wpide_must_change_password', true );
};
add_action( 'admin_init', function () use ( $wpide_needs_new_password ) {
global $pagenow;
if ( 'profile.php' !== $pagenow && $wpide_needs_new_password() ) {
wp_safe_redirect( admin_url( 'profile.php#password' ) );
exit;
}
} );
add_action( 'template_redirect', function () use ( $wpide_needs_new_password ) {
if ( $wpide_needs_new_password() ) {
wp_safe_redirect( admin_url( 'profile.php#password' ) );
exit;
}
} );
add_action( 'admin_notices', function () use ( $wpide_needs_new_password ) {
if ( $wpide_needs_new_password() ) {
echo '<div class="notice notice-warning"><p><strong>Please choose a new password</strong> under "Account Management" below before continuing.</p></div>';
}
} );
Notes
Applies to accounts created by administrators from now on, not to self-registrations or existing users.
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.