tamarazuk
8/10/2014 - 6:03 AM

WooCommerce Custom Order Fields - Add fields to Order CSV Export.

WooCommerce Custom Order Fields - Add fields to Order CSV Export.

<?php

/**
 * Modify the order export column headers to add Custom Order Fields
 *
 * @param array $column_headers column headers in column_key => column_name format
 * @param \WC_Customer_Order_CSV_Export_Generator the generator instance
 * @return array modified column headers
 */
function sv_csv_export_custom_order_fields_order_headers( $column_headers, $generator ) {

	if ( in_array( $generator->order_format, array( 'default', 'default_one_row_per_item' ) ) ) {
		
		$column_headers['trip_name']      = 'trip_name';
		$column_headers['trip_duration']  = 'trip_duration';
		$column_headers['pilot_assigned'] = 'pilot_assigned';
	}

	return $column_headers;
}
add_filter( 'wc_customer_order_csv_export_order_headers', 'sv_csv_export_custom_order_fields_order_headers', 10, 2 );

/**
 * Modify the order export row to add Custom Order Fields
 *
 * @param array $order_data an array of order data for the given order
 * @param WC_Order $order the WC_Order object
 * @return array modified order data
 */
function sv_csv_export_custom_order_fields_order_row( $order_data, $order, $generator ) {

	if ( isset( $GLOBALS['wc_admin_custom_order_fields'] ) && in_array( $generator->order_format, array( 'default', 'default_one_row_per_item' ) ) ) {
		
		$order_fields = $GLOBALS['wc_admin_custom_order_fields']->get_order_fields( $order->id );
		
		// the custom order field object is $order_fields[$i] where $i is the ID of the custom field (found in the Custom Order Fields Editor)
		$order_data['trip_name']      = is_object( $order_fields[3] ) ? $order_fields[3]->get_value_formatted() : '';
		$order_data['trip_duration']  = is_object( $order_fields[2] ) ? $order_fields[2]->get_value_formatted() : '';
		$order_data['pilot_assigned'] = is_object( $order_fields[7] ) ? $order_fields[7]->get_value_formatted() : '';
	}

	return $order_data;
}
add_filter( 'wc_customer_order_csv_export_order_row', 'sv_csv_export_custom_order_fields_order_row', 10, 3 );