Home > Software engineering >  Adding some editable fields to admin page order
Adding some editable fields to admin page order

Time:10-22

I'm trying to add an editable custom field into the admin page order. It's a car service website and I need to insert the total auto kilometers when an order is completed. I can see the field on the page but it doesn't save and show any value when I update the order. This is the code that I added to the function.php:

add_action( 'woocommerce_admin_order_data_after_order_details', 'editable_order_custom_field', 12, 1 );
function editable_order_custom_field( $order ){
    // custom editable field
    woocommerce_wp_text_input( array(
        'id'            => 'custom_km',
        'label'         => __("Total Km:", "woocommerce"),
        'value'         => $value,
        'wrapper_class' => 'form-field-wide',
    ) );
}

Any help is very very appreciated.

CodePudding user response:

You need to save the data to the database.

add_action( 'woocommerce_process_shop_order_meta', 'save_custom_filed_data' );

function save_custom_filed_data( $order_id ){
    update_post_meta( $order_id, 'custom_km', wc_clean( $_POST['custom_km'] ) );
}

Then you can retrieve the data in the following way. Here, I've shown the data after the billing address, which you can display in your desired place by a hook.

add_action('woocommerce_admin_order_data_after_billing_address', 'display_the_custom_distance_km', 10, 1);
function display_the_custom_distance_km($order)
{
    echo '<p><strong>Custom Km:</strong><br>' . get_post_meta($order->get_ID(), 'custom_km', true) . '</p>';
}
  • Related