Search code examples
phpwordpresswoocommercecustom-fieldsaccount

WooCommerce: Validate custom fields on My Account's edit page


I've added custom fields to my WooCommerce registration using this process. I've made them available on the My Account's edit page using these actions:

// added custom fields here
add_action( 'woocommerce_edit_account_form', 'my_woocommerce_edit_account_form' );   

// saved user meta here
add_action( 'woocommerce_save_account_details', 'my_woocommerce_save_account_details' );

In between the two, I need to validate these fields when editing. I tried using the woocommerce_process_myaccount_field_ filter (as mentioned here) but that didn't work. The code inside it doesn't trigger when I save the changes.

Any ideas on how can I validate?
Am I using the correct filter?
If yes, why doesn't it trigger?

Thanks.


Solution

  • You could try to use one of this 2 hooks for validating custom fields.

    add_action( 'user_profile_update_errors','wooc_validate_custom_field', 10, 1 );
    
    // or
    
    add_action( 'woocommerce_save_account_details_errors','wooc_validate_custom_field', 10, 1 );
    
    // with something like:
    
    function wooc_validate_custom_field( $args )
    {
        if ( isset( $_POST['custom_field'] ) ) // Your custom field
        {
            if(strlen($_POST['custom_field'])<4 ) // condition to be adapted
            $args->add( 'error', __( 'Your error message', 'woocommerce' ),'');
        }
    }