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

Sha*_*wer 3 php wordpress woocommerce hook-woocommerce

我想在通过“我的帐户”页面更新地址时在计费电话上添加验证。

表格位置: 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' );
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

你们中有人能看出我做错了什么吗?如果它是一个错误的动作钩子或者缺少一些功能?

Sha*_*wer 5

add_action( "woocommerce_after_save_address_validation",'custom_validation',1,2);
Run Code Online (Sandbox Code Playgroud)

  • 请考虑对此答案添加评论。不鼓励仅使用代码答案。 (3认同)
  • 虽然此代码可以回答问题,但提供有关如何和/或为何解决问题的附加上下文将提高​​答案的长期价值。 (2认同)