使用 Hook 在我的帐户页面上更新 Woocommerce 地址验证

Woocommerce Address Update Validation on My Account Page using Hook

我想在通过“我的帐户”页面更新地址时添加对帐单的验证 phone。

表单位置:http://www.example.com/my-account/edit-address/billing

我的代码如下:-

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

我在提交表单后收到了定义的通知(我在上面的代码中定义的),但就在它下面,也出现了一个成功的通知,并且正在更新数据。这只是意味着我的代码不起作用。

你们谁能看出我做错了什么吗?如果它是一个错误的动作挂钩或缺少功能?

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

我会在答案中添加评论,但我的声誉等级不允许我:)。 该代码有效,因为 add_action 是这样工作的:

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

最后一个参数表示 $function_to_add 的参数数量,在本例中为

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.

个人讨厌自我推销,有一个插件可以帮助解决这个问题(希望它现在还能用,好久没更新了):https://wordpress.org/plugins/woo-phone-validator/ 如果它不起作用,您可以随时恢复为自定义代码答案。