Woocommerce 上的自定义结帐字段验证

Custom checkout field validation on Woocommerce

我的代码:

add_action( 'woocommerce_before_checkout_form', 'fruit_field' );

function fruit_field( $checkout ) {

  woocommerce_form_field( 'fruit', array(
      'type'          => 'select',
      'required'      => true,
      'options'       => array(
        'apple'       => __('Apple'),
        'banana'      => __('Banana'),
        'watermelon'  => __('Watermelon'),
        'other'       => __('Other'),
      ),
      'class'         => array('my-class'),
      'label'         => __('Best fruit?'),
      ), $checkout->get_value( 'fruit' ));
}

和验证:

add_action('woocommerce_checkout_process', 'process_checkout');

function process_checkout() {
  if ($_POST['fruit'] === null) {
    wc_add_notice( __( 'No fruits?' ), 'error' );
  }
}

提交表单后,无论选择什么,它总是显示我的自定义错误 "No fruits?"。 $_POST['fruit'] 是否在 process_checkout 函数中不可用?

You can not use custom checkout fields in woocommerce_before_checkout_form hook as your field is outside the checkout form, and it is not posted on submit.

相反,您应该使用 woocommerce_checkout_before_customer_details 动作挂钩:

add_action( 'woocommerce_checkout_before_customer_details', 'fruit_custom_checkout_field' );
function fruit_custom_checkout_field() {

    woocommerce_form_field( '_fruit', array(
        'type'     => 'select',
        'label'    => __('Best fruit?'),
        'class'    => array('my-fruit'),
        'required' => true,
        'options'  => array(
            ''          => __('Chose a fruit'),
            'Apple'      => __('Apple'),
            'Banana'     => __('Banana'),
            'Watermelon' => __('Watermelon'),
            'Other'      => __('Other'),
        ),
    ), WC()->checkout->get_value('_fruit') );
}

add_action('woocommerce_checkout_process', 'process_fruit_custom_checkout_field');
function process_fruit_custom_checkout_field() {
    if (isset($_POST['_fruit']) && empty($_POST['_fruit']) ) {
        wc_add_notice( __( 'please choose a "fruits"' ), 'error' );
    }
}

// Save the custom checkout field in the order meta
add_action( 'woocommerce_checkout_create_order', 'save_fruit_custom_field_as_meta_data', 10, 2 );
function save_fruit_custom_field_as_meta_data( $order, $data ) {
    if (isset($_POST['_fruit']) && ! empty($_POST['_fruit']) ) {
        $order->update_meta_data('_custom_field', esc_attr( $_POST['_fruit'] ) );
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。