2 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
要使自定義字段billing_vat成為必填項(xiàng),當(dāng)國(guó)家/地區(qū)設(shè)置為愛(ài)爾蘭 (IE) 時(shí)。
只需將您現(xiàn)有的代碼替換為:(通過(guò)注釋標(biāo)簽進(jìn)行解釋?zhuān)砑拥酱a中)
// 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貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
只需將以下代碼片段添加到您現(xiàn)有的代碼片段中,希望您將完成管理愛(ài)爾蘭的驗(yàn)證
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 關(guān)注
- 189 瀏覽
添加回答
舉報(bào)