2 回答
TA贡献1862条经验 获得超6个赞
要使自定义字段billing_vat成为必填项,当国家/地区设置为爱尔兰 (IE) 时。
只需将您现有的代码替换为:(通过注释标签进行解释,添加到代码中)
// Add field
function filter_woocommerce_billing_fields( $fields ) {
$fields['billing_vat'] = array(
'label' => 'VAT Number',
'required' => false,
'type' => 'text',
'class' => array( 'form-row-wide' ),
'priority' => 35,
);
return $fields;
}
add_filter( 'woocommerce_billing_fields', 'filter_woocommerce_billing_fields', 10, 1 );
// Validate
function action_woocommerce_after_checkout_validation( $data, $error ) {
if ( $data['billing_country'] == 'IE' && empty( $data['billing_vat'] ) ) {
$error->add( 'validation', 'Required based on country.' );
}
}
add_action('woocommerce_after_checkout_validation', 'action_woocommerce_after_checkout_validation', 10, 2 );
// jQuery
function action_woocommerce_after_order_notes( $checkout ) {
?>
<script>
(function($) {
$(document).ready(function () {
required_or_optional(); //this calls it on load
$( '#billing_country' ).change( required_or_optional );
function required_or_optional() {
if ( $( '#billing_country' ).val() == 'IE' ) {
// Required
$( '#billing_vat' ).prop( 'required', true );
$( 'label[for="billing_vat"] .optional' ).remove();
$( 'label[for="billing_vat"]' ).append( '<abbr class="required" title="required">*</abbr>' );
} else {
$( '#billing_vat' ).removeProp( 'required' );
$( 'label[for="billing_vat"] .required' ).remove();
// Avoid append this multiple times
if ( $( 'label[for="billing_vat"] .optional' ).length == 0 ) {
$( 'label[for="billing_vat"]' ).append( '<span class="optional">(optional)</span>' );
}
}
}
});
})(jQuery);
</script>
<?php
}
add_action( 'woocommerce_after_order_notes', 'action_woocommerce_after_order_notes', 10, 1 );
// Display on the order edit page (backend)
function action_woocommerce_admin_order_data_after_shipping_address( $order ) {
if ( $value = $order->get_meta( '_billing_vat' ) ) {
echo '<p><strong>' . __( 'Billing VAT', 'woocommerce' ) . ':</strong> ' . $value . '</p>';
}
}
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'action_woocommerce_admin_order_data_after_shipping_address', 10, 1 );
TA贡献1828条经验 获得超3个赞
只需将以下代码片段添加到您现有的代码片段中,希望您将完成管理爱尔兰的验证
add_action('woocommerce_checkout_process', 'billing_vat_field_process');
function billing_vat_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['billing_vat'] && !empty($_POST['billing_country']) &&
$_POST['billing_country'] == "IE" ){
wc_add_notice( __( 'Please enter VAT number' ), 'error' );
}
}
- 2 回答
- 0 关注
- 156 浏览
添加回答
举报