Halloween Sale 15% off Ends in See the plans
PHP

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.

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

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

  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.