woocommerce 结帐自定义字段更新订单元

问题描述

基于@LoicTheAztec 的这个https://stackoverflow.com/a/49163797/7783506,我能够创建关于统一费率运输方式的自定义字段,我可以在 MysqL 上找到数据,但它没有显示在订单详细信息、电子邮件中。 如何将其添加到订单详细信息和电子邮件中?这是我根据该帖子使用的代码

// Add custom fields to a specific selected shipping method
add_action( 'woocommerce_after_shipping_rate','carrier_custom_fields',20,2 );
function carrier_custom_fields( $method,$index ) {
    if( ! is_checkout()) return; // Only on checkout page

    $customer_carrier_method = 'flat_rate:4';

    if( $method->id != $customer_carrier_method ) return; // Only display for "local_pickup"

    $chosen_method_id = WC()->session->chosen_shipping_methods[ $index ];

    // If the chosen shipping method is 'legacy_local_pickup' we display
    if($chosen_method_id == $customer_carrier_method ):

    echo '<div class="custom-carrier">';

    woocommerce_form_field( 'ds_name',array(
        'type'          => 'text','class'         => array('form-row-wide ds-name'),'required'      => true,'placeholder'   => 'Nama Toko',),WC()->checkout->get_value( 'ds_name' ));

    woocommerce_form_field( 'ds_number','class'         => array('form-row-wide ds-number'),'placeholder'   => 'Kode Booking',WC()->checkout->get_value( 'ds_number' ));

    echo '</div>';
    endif;
}

// Check custom fields validation
add_action('woocommerce_checkout_process','carrier_checkout_process');
function carrier_checkout_process() {
    if( isset( $_POST['ds_name'] ) && empty( $_POST['ds_name'] ) )
        wc_add_notice( ( "Anda belum memasukkan Nama Toko" ),"error" );

    if( isset( $_POST['ds_number'] ) && empty( $_POST['ds_number'] ) )
        wc_add_notice( ( "Anda belum memasukkan nomor kode booking" ),"error" );
}

// Save custom fields to order Meta data
add_action( 'woocommerce_checkout_update_order_Meta','carrier_update_order_Meta',30,1 );
function carrier_update_order_Meta( $order_id ) {
    if( isset( $_POST['ds_name'] ))
        update_post_Meta( $order_id,'_ds_name',sanitize_text_field( $_POST['ds_name'] ) );

    if( isset( $_POST['ds_number'] ))
        update_post_Meta( $order_id,'_ds_number',sanitize_text_field( $_POST['ds_number'] ) );
}

解决方法

找到解决方案,删除 update_post_meta 上的 _(下划线),然后在订单编辑时显示。

// Save custom fields to order meta data
add_action( 'woocommerce_checkout_update_order_meta','carrier_update_order_meta',30,1 );
function carrier_update_order_meta( $order_id ) {
    if( isset( $_POST['ds_name'] ))
        update_post_meta( $order_id,'ds_name',sanitize_text_field( $_POST['ds_name'] ) );

    if( isset( $_POST['ds_number'] ))
        update_post_meta( $order_id,'ds_number',sanitize_text_field( $_POST['ds_number'] ) );
}