Sca*_*ola 3 php wordpress checkout woocommerce hook-woocommerce
有时,在 WooCommerce 中,客户需要在一个字段中填写街道名称和门牌号。
在这种情况下,我们希望在处理订单之前验证 billing_address_1 WooCommerce 结账字段以检查它是否包含数字。我们尝试了多种方法来完成这项工作,但没有任何运气。
这个标准的 WooCommerce 方法不起作用:
add_action('woocommerce_checkout_process', 'custom_checkout_field_check');
function custom_checkout_field_check() {
// Check if set, if its not set add an error.
if ( $_POST['billing_address_1'] && strpbrk($_POST['billing_address_1'], '1234567890') )
wc_add_notice( __( 'Het adresveld moet minimaal een huisnummer bevatten' ), 'error' );
}
Run Code Online (Sandbox Code Playgroud)
这些在结帐页面上返回 bool(false):
var_dump($_POST['billing_address_1'] == true);
var_dump($_POST['billing_address_2'] == true);
var_dump($_POST['billing_postcode'] == true);
var_dump($_POST['billing_email'] == true);
Run Code Online (Sandbox Code Playgroud)
这种前端解决方法不起作用。
document.querySelector("#place_order").addEventListener("click", validateAddressField);
function validateAddressField () {
console.log('Okay dan!');
}
Run Code Online (Sandbox Code Playgroud)
我还可以尝试哪些方法来确保在处理订单之前进行验证?
这在您的代码中无法正常工作:strpbrk($_POST[\'billing_address_1\'], \'1234567890\')
。
\nPHP 函数preg_match()
用在这里更合适。
因此,我对您的代码做了一些小更改,以使其按您的预期工作:
\n\nadd_action(\'woocommerce_checkout_process\', \'address_field_validation\', 10, 0);\nfunction address_field_validation() {\n\n // The field value to check\n $post_value = $_POST[\'billing_address_1\'];\n\n // If there is no number in this field value, stops the checkout process\n // and displays an error message.\n if ( $post_value && ! preg_match( \'/[0-9]+/\', $post_value ) ) {\n\n // The error message\n throw new Exception( sprintf( __( \'Het adresveld moet minimaal een huisnummer bevatten\', \'woocommerce\' ) ) );\n }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n此代码经过测试并适用于 WooCommerce 版本 2.6.x 和 3.0+\xe2\x80\xa6
\n\n*此代码位于活动子主题(或主题)的 function.php 文件中或任何插件文件中。
\n\n参考:WC_Checkout - process_checkout() 源代码
\n // Check if address field contains house number otherwise provide error message
add_action( 'woocommerce_after_checkout_validation', 'validate_checkout', 10, 2);
function validate_checkout( $data, $errors ){
if ( ! preg_match('/[0-9]/', $data[ 'billing_address_1' ] ) ){
$errors->add( 'address', 'Sorry, but the address you provided does not contain a house number.' );
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2811 次 |
最近记录: |