How to add woocommerce custom order data?

by ryan.murray , in category: PHP CMS , a year ago

How to add woocommerce custom order data?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , a year ago

@ryan.murray 

To add WooCommerce custom order data, you can use the following steps:

  1. Create a custom plugin or use the functions.php file in your child theme to add the code.
  2. Use the woocommerce_process_shop_order_meta hook to add custom fields to the admin order page. Here's an example code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
add_action( 'woocommerce_process_shop_order_meta', 'add_custom_order_data' );
function add_custom_order_data( $order_id ) {
    // Get the order object
    $order = new WC_Order( $order_id );

    // Add custom order data
    $custom_field_value = get_post_meta( $order_id, '_custom_field', true );
    if ( ! empty( $custom_field_value ) ) {
        $order->add_order_note( 'Custom field: ' . $custom_field_value );
    }
}


  1. Use the woocommerce_checkout_create_order hook to save custom data when an order is created. Here's an example code snippet:
1
2
3
4
5
add_action( 'woocommerce_checkout_create_order', 'save_custom_order_data' );
function save_custom_order_data( $order ) {
    $custom_field_value = sanitize_text_field( $_POST['custom_field'] );
    $order->update_meta_data( '_custom_field', $custom_field_value );
}


  1. Display custom order data on the frontend using the woocommerce_order_details_after_order_table hook. Here's an example code snippet:
1
2
3
4
5
6
7
add_action( 'woocommerce_order_details_after_order_table', 'display_custom_order_data' );
function display_custom_order_data( $order ) {
    $custom_field_value = get_post_meta( $order->get_id(), '_custom_field', true );
    if ( ! empty( $custom_field_value ) ) {
        echo '<p><strong>Custom Field:</strong> ' . $custom_field_value . '</p>';
    }
}


By following these steps, you can easily add custom order data to your WooCommerce orders.

Related Threads:

How to add woocommerce custom order status?
How to create a custom order status in woocommerce?
How to add order by dropdown to woocommerce?
How to get updated woocommerce order data?
How to add custom email notification in woocommerce?
How to add custom registration fields to woocommerce?