0

based on this https://stackoverflow.com/a/49163797/7783506 by @LoicTheAztec I was able to create the custom fields on flat rate shipping method, I could find the data on MySQL, but it was not showing on the order detail, email. How do I add this to order details and email? here's the code that i use based on that post

// 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'] ) );
}

1 Answers1

0

found the solution, removing _ (underscore) on update_post_meta then it show on order edit.

// 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'] ) );
}