【问题标题】:Save Multiselect custom filed on woocommerce product page在 woocommerce 产品页面上保存多选自定义字段
【发布时间】:2021-04-08 21:03:01
【问题描述】:

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

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' );

【问题讨论】:

  • 这将不起作用,因为当您进行多项选择时,您的多选字段仅发布最后选择的值...您需要自定义多选字段 html...
  • 有点混乱!

标签: php woocommerce hook-woocommerce multi-select custom-fields


【解决方案1】:

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

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' );

【讨论】:

  • 是的,我试过了,但我得到了同样的结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多