How is wp_admin_notice supposed to work?

If you look at the user-edit.php file, you can see, when updating an user, if there are no errors, then WP performs an redirect. This effectively wipes the admin notice you’re trying to display as it is not stored anywhere.

One workaround for this is to store the custom error as a temporary option value and then display the error on admin_notices after the redirect.

function wpse427457_error_option(): string {
    return 'wpse427457_error';
}

add_action( 'edit_user_profile_update', 'wpse427457_save_user_data' );
function wpse427457_save_user_data( int $user_id ): void {
    $invalid = true;

    if ( $invalid ) {
        update_option( wpse427457_error_option(), __( 'Error', 'textdomain' ), false );
    }
}

add_action( 'admin_notices', 'wpse427457_display_user_data_error' );
function wpse427457_display_user_data_error(): void {
    $error = get_option( wpse427457_error_option() );

    if ( $error ) {
        wp_admin_notice(
            $error,
            array(
                'type' => 'error',
                'dismissible' => true,
            )
        );

        delete_option( wpse427457_error_option() );
    }
}

Another option is to add an action to user_profile_update_errors on edit_user_profile_update when the custom field validation fails to display a custom error message. This hook fires inside edit_user(), which is executed after edit_user_profile_update to update the user.

edit_user() returns WP_Error, which is populated both by default user field validation errors and from the user_profile_update_errors action, if any errors occured during the user update. This error object then prevents the user-edit.php redirect from happening and the error is passed to wp_admin_notice() later in the file to display the notices.

add_action( 'edit_user_profile_update', 'wpse427457_save_user_data' );
function wpse427457_save_user_data( int $user_id ): void {
    $invalid = true;

    if ( $invalid ) {
        add_action( 'user_profile_update_errors', 'wpse427457_add_data_mismatch_error', 10, 3 );
    }
}

function wpse427457_add_data_mismatch_error( WP_Error &$errors, bool $update, stdClass &$user ) {
    $errors->add( 'wpse427457_data_mismatch', __( 'Error', 'textdomain' ), array( 'details' => '' ) );
}

techhipbettruvabetnorabahisbahis forumuedueduedueduedusedueduseduedusedus