我想要创建一个 WooCommerce 结账字段,该字段仅在选择特定付款(货到付款)时显示。仅当选择货到付款时,才应显示此字段并且仅需要此字段。我已经设法创建该字段并有条件地显示它,但我无法弄清楚如何仅在选择 COD 时才需要它。
/* Only show EAN when COD chosen */
// Conditional Show hide checkout fields based on chosen payment methods
add_action( 'wp_footer', 'conditionally_show_hide_billing_custom_field' );
function conditionally_show_hide_billing_custom_field(){
// Only on checkout page
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?>
<script>
jQuery(function($){
var a = 'input[name="payment_method"]',
b = a + ':checked',
c = '#billing_options_field'; // The checkout field <p> container selector
// Function that shows or hide checkout fields
function showHide( selector = '', action = 'show' ){
if( action == 'show' )
$(selector).show( 200, function(){
$(this).addClass("validate-required");
});
else
$(selector).hide( 200, function(){
$(this).removeClass("validate-required");
});
$(selector).removeClass("woocommerce-validated");
$(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
}
// Initialising: Hide if choosen payment method is "cod"
if( $(b).val() !== 'cod' )
showHide( c, 'hide' );
else
showHide( c );
// Live event (When payment method is changed): Show or Hide based on "cod"
$( 'form.checkout' ).on( 'change', a, function() {
if( $(b).val() !== 'cod' )
showHide( c, 'hide' );
else
showHide( c );
});
});
</script>
<?php
endif;
}
/* Add extra field and make it required */
add_filter('woocommerce_billing_fields', 'custom_woocommerce_billing_fields');
function custom_woocommerce_billing_fields($fields)
{
$fields['billing_options'] = array(
'label' => __('– EAN-nummer – ', 'woocommerce'), // Add custom field label
'placeholder' => _x('EAN nummer', 'placeholder', 'woocommerce'), // Add custom field placeholder
'required' => true, // if field is required or not
'clear' => false, // add clear or not
'type' => 'text', // add field type
'class' => array('my-css') // add class name
);
return $fields;
}
最佳答案
add_action('woocommerce_after_checkout_validation', 'woocommerce_after_checkout_validation_alter', 10, 2);
function woocommerce_after_checkout_validation_alter($data, $errors){
if('cod' !== $data['payment_method']){
if($errors->get_error_data('billing_options_required')){ // This will contain the error
$errors->remove('billing_options_required');
}
}
return $data;
}
如果选择的付款方式不是 COD,则从错误对象中删除验证错误。错误对象如下所示。
WP_Error Object
(
[errors] => Array
(
[billing_options_required] => Array
(
[0] => <strong>Billing – EAN-nummer – </strong> is a required field.
)
)
[error_data] => Array
(
[billing_options_required] => Array
(
[id] => billing_options
)
)
[additional_data:protected] => Array
(
)
)
关于php - 有条件必填的 WooCommerce 结帐字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75457769/