保存在 woocommerce 产品页面上提交的多选自定义

问题描述

当我尝试从多选自定义字段中检索数据时,我只得到数组键而不是如下值:

array (size=2)
  0 => string '0' (length=1)
  1 => string '1' (length=1)

这是自定义字段代码

function cfwc_create_custom_field() {
    $args = array(
    'id' => 'custom_text_field_title','name' => 'custom_text_field_title[]','label' => __( 'Custom Text Field Title','cfwc' ),'class' => 'cfwc-custom-field','desc_tip' => true,'options'  => array('First','Second'),'description' => __( 'Enter the title of your custom text field.','ctwc' ),'custom_attributes' => array('multiple' => 'multiple')
    );
    woocommerce_wp_select( $args );
}
add_action( 'woocommerce_product_options_general_product_data','cfwc_create_custom_field' );

function cfwc_save_custom_field( $post_id ) {
    $product = wc_get_product( $post_id );
    $title = isset( $_POST['custom_text_field_title'] ) ? $_POST['custom_text_field_title'] : '';
    $product->update_Meta_data( 'custom_text_field_title',$_POST['custom_text_field_title'] );
    $product->save();
}
add_action( 'woocommerce_process_product_Meta','cfwc_save_custom_field' );

解决方法

我认为您的问题是您提供的 woocommerce_wp_select 选项,因为您使用了选项 array('First','Second') 因为没有键,只要它简单地将 0,1 值作为数组返回。所以如果你想要 key 那么你必须为 Ex: array('First' => 'First','Second' => 'Second') 提供它,或者 key 只是你喜欢的小写字母。

function cfwc_create_custom_field() {
    $args = array(
    'id' => 'custom_text_field_title','name' => 'custom_text_field_title[]','label' => __( 'Custom Text Field Title','cfwc' ),'class' => 'cfwc-custom-field','desc_tip' => true,'options'  => array('First' => 'First','Second' => 'Second'),// this is correct
    'description' => __( 'Enter the title of your custom text field.','ctwc' ),'custom_attributes' => array('multiple' => 'multiple')
    );
    woocommerce_wp_select( $args );
}
add_action( 'woocommerce_product_options_general_product_data','cfwc_create_custom_field' );

function cfwc_save_custom_field( $post_id ) {
    $product = wc_get_product( $post_id );
    $title = isset( $_POST['custom_text_field_title'] ) ? $_POST['custom_text_field_title'] : '';
    $product->update_meta_data( 'custom_text_field_title',$_POST['custom_text_field_title'] );
    $product->save();
}
add_action( 'woocommerce_process_product_meta','cfwc_save_custom_field' );