Search code examples
phpwordpresswoocommercehook-woocommerce

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?


Solution

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