0

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']));
    }
}

fcastillo
  • 938
  • 1
  • 11
  • 24
  • 1
    You can use the `woocommerce_save_account_details_required_fields` filter hook, see this [answer](https://stackoverflow.com/a/61115472/11987538) or this [answer](https://stackoverflow.com/questions/70585051/add-a-custom-dropdown-field-on-my-account-edit-account-in-woocommerce/70591364#70591364) – 7uc1f3r Feb 14 '22 at 17:51
  • @7uc1f3r Yes, that's what i was looking for! THX!!! – fcastillo Feb 14 '22 at 17:58

0 Answers0