WooCommerce结账账单区域添加自定义字段出现重复字段问题
解决WooCommerce结账账单区域出现重复自定义字段的问题
你出现两个字段的原因很明确:同时用了两种方式添加同一个自定义字段——一边通过woocommerce_checkout_fields过滤器把字段加入账单字段集合,另一边又通过woocommerce_after_checkout_billing_form动作手动渲染了一遍相同的字段,自然会重复。
修正方案二选一即可:
方案1:用过滤器规范添加(推荐,自动适配WooCommerce样式)
删掉display_custom_checkout_field函数及其对应的动作钩子,只保留woocommerce_checkout_fields过滤器的代码。如果想把字段放在账单区域最底部,给字段加个priority参数调整位置:
// Add a custom text field to WooCommerce checkout billing section add_filter('woocommerce_checkout_fields', 'custom_checkout_field'); function custom_checkout_field($fields) { $fields['billing']['custom_text_field'] = array( 'type' => 'text', 'class' => array('form-row-wide'), 'label' => __('Custom Text Field', 'woocommerce'), 'placeholder' => __('Enter your custom text', 'woocommerce'), 'required' => true, 'priority' => 100 // 数值越大位置越靠后,默认账单字段优先级多在10-50区间 ); return $fields; } // Save the custom text field value to the order meta add_action('woocommerce_checkout_update_order_meta', 'save_custom_checkout_field'); function save_custom_checkout_field($order_id) { if (!empty($_POST['custom_text_field'])) { update_post_meta($order_id, '_custom_text_field', sanitize_text_field($_POST['custom_text_field'])); } }
方案2:手动渲染字段(适合需要完全自定义布局的场景)
删掉woocommerce_checkout_fields过滤器及其对应的函数,只保留手动渲染的代码,这样就不会在woocommerce-billing-fields__field-wrapper里多出一个字段:
// Save the custom text field value to the order meta add_action('woocommerce_checkout_update_order_meta', 'save_custom_checkout_field'); function save_custom_checkout_field($order_id) { if (!empty($_POST['custom_text_field'])) { update_post_meta($order_id, '_custom_text_field', sanitize_text_field($_POST['custom_text_field'])); } } // Display the custom text field on the checkout page add_action('woocommerce_after_checkout_billing_form', 'display_custom_checkout_field'); function display_custom_checkout_field($checkout) { ?> <div id="custom_checkout_field_display"> <h3><?php _e('Custom Text Field'); ?></h3> <div class="custom-text-field-wrapper"> <?php woocommerce_form_field('custom_text_field', array( 'type' => 'text', 'class' => array('form-row-wide'), 'label' => __('Custom Text Field', 'woocommerce'), 'placeholder' => __('Enter your custom text', 'woocommerce'), 'required' => true, ), $checkout->get_value('custom_text_field')); ?> </div> </div> <?php }
两种方案都能解决重复字段的问题,按需选择即可。
内容的提问来源于stack exchange,提问作者Filippo
相关产品推荐
相关产品推荐

