简体   繁体   中英

Woocommerce Address Update Validation on My Account Page using Hook

I want to add a validation on billing phone when the address is updated through the My Account Page.

Form Location: http://www.example.com/my-account/edit-address/billing

My Code so far as below:-

add_action( "woocommerce_customer_save_address", 'custom_validation'); 

function custom_validation($user_id,$load_address)
{
    if ( $user_id <= 0 )
    {
        return;
    }

    if(isset($_POST['billing_phone']))
    {
        $account_billing_phone   = ! empty( $_POST['billing_phone'] ) ? wc_clean( $_POST['billing_phone'] ) : '';
        $get_user                = wp_get_current_user();
        $user_phone = get_user_meta( $get_user->ID, 'billing_phone', true );
        if(strlen($account_billing_phone) !== 10 )
        {
            wc_add_notice( __( 'Enter a valid 10 digit mobile number', 'woocommerce' ), 'error' );
        }
        elseif($account_billing_phone !== $user_phone)
        {
            $user_exist = get_users(array('meta_value' => array($account_billing_phone)));
            if($user_exist)
            {
                wc_add_notice( __( 'Mobile number already exist.', 'woocommerce' ), 'error' );
            }
        }
    }
}

I am getting the defined Notices (that i defined in the code above) after submitting the form, but just below it, a successful notice is also appearing, and the data is being updated. It simply means my codes are not working.

Can any one of you see what i am doing wrong? If its a wrong action hook or something missing is function?

add_action( "woocommerce_after_save_address_validation",'custom_validation',1,2);

I would have added a comment to the answer, but my reputation rank won't let me :) . That code works because add_action works like this:

add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )

The last argument states the number of arguments the $function_to_add has, which in this case is

custom_validation($user_id,$load_address) It's best practice to state the number of arguments your function will be having and also set the priority number. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM