Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 435
sgr12 Avatar asked Oct 26 '25 14:10

sgr12


1 Answers

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' ),'');
    }
}
like image 75
LoicTheAztec Avatar answered Oct 29 '25 04:10

LoicTheAztec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!