user_login === 'admin' ) { update_option( 'ns_shield_admin_login_change_pending', $new_admin_login ); } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->update( $wpdb->users, array( 'user_login' => sanitize_user( $new_admin_login ) ), array( 'ID' => $admin_user->ID ) ); clean_user_cache( $admin_user->ID ); } } } } else { $custom_admin_login = get_option( 'ns_shield_new_admin_login', '' ); if ( ! empty( $custom_admin_login ) ) { $custom_user = get_user_by( 'login', $custom_admin_login ); if ( $custom_user ) { if ( wp_get_current_user()->user_login === $custom_admin_login ) { update_option( 'ns_shield_admin_login_change_pending', 'admin' ); } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->update( $wpdb->users, array( 'user_login' => 'admin' ), array( 'ID' => $custom_user->ID ) ); clean_user_cache( $custom_user->ID ); } } } } } add_action( 'init', 'ns_shield_update_admin_username' ); /** * Changes the admin username after logout if there's a pending change. * * This function checks if there is a pending admin username change and updates it accordingly. * * @global WPDB $wpdb * @return void */ function ns_shield_change_admin_username_after_logout() { global $wpdb; $pending_login_change = get_option( 'ns_shield_admin_login_change_pending', '' ); if ( ! empty( $pending_login_change ) ) { $target_login = ( $pending_login_change === 'admin' ) ? get_option( 'ns_shield_new_admin_login', '' ) : 'admin'; $admin_user = get_user_by( 'login', $target_login ); if ( $admin_user ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->update( $wpdb->users, array( 'user_login' => sanitize_user( $pending_login_change ) ), array( 'ID' => $admin_user->ID ) ); clean_user_cache( $admin_user->ID ); delete_option( 'ns_shield_admin_login_change_pending' ); } } } add_action( 'wp_logout', 'ns_shield_change_admin_username_after_logout' );