I want to add some fields to customer profile and I have added following this question
This works good if my fields aren't required, but how can I do them required and show an error when customer doesn't fill them?
With this code I can add an error but it appears after another ok message and redirect to "my account" page:
add_action('woocommerce_edit_account_form', 'add_favorite_color_to_edit_account_form');
function add_favorite_color_to_edit_account_form()
{
$user = wp_get_current_user();
?>
<p class="woocommerce-form-row woocommerce-form-row--first form-row form-row-first">
<label for="favorite_color"><?php _e('Favorite color', 'woocommerce'); ?>
<input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="favorite_color" id="favorite_color" value="<?php echo esc_attr($user->favorite_color); ?>" />
</p>
<?php
}
add_action('woocommerce_save_account_details', 'save_favorite_color_account_details', 12, 1);
function save_favorite_color_account_details($user_id)
{
$fav_color = $_POST['favorite_color'];
if (empty($fav_color)) {
wc_add_notice(__('Fav color is required!', 'xxxxx'), 'error');
} else {
update_user_meta($user_id, 'favorite_color', sanitize_text_field($_POST['favorite_color']));
}
}