WooCommerce签出自定义字段更新订单元字段、单元、定义、WooCommerce

2023-09-03 14:41:10 作者:只是,习惯了你的习惯

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

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
// 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' , array(
        'type'          => 'text',
        'class'         => array('form-row-wide ds-number'),
        'required'      => true,
        '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上的_(下划线),然后在订单编辑上显示。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
// 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'] ) );
}