Search code examples
phpwordpresswoocommerceexportorders

WooCommerce Customer/Order CSV Export - Add Column as first column


I am using WooCommerce Customer/Order CSV Export and have a snippet in my functions file (obtained from WooCommerce.

    function sv_wc_csv_export_reorder_columns( $column_headers ) {
        // remove order total from the original set of column headers, otherwise it will be duplicated
        unset( $column_headers['column_1'] );
        unset( $column_headers['delivery_date'] );
        $new_column_headers = array();
        foreach ( $column_headers as $column_key => $column_name ) {
            $new_column_headers[ $column_key ] = $column_name;
            if ( 'shipping_company' == $column_key ) {
                // add order total immediately after order_number
                $new_column_headers['column_1'] = 'Contact Name';
            }
        }
        return $new_column_headers;
    }
    add_filter( 'wc_customer_order_csv_export_order_headers', 'sv_wc_csv_export_reorder_columns' );

The problem as is with the code, it adds column_1 directly after shipping_company (the first field) - how can I set it so that it appears before this column or set it as the first column?


Solution

  • You need simply the following to set or add 'column_1' as first column:

    add_filter( 'wc_customer_order_csv_export_order_headers', 'sv_wc_csv_export_reorder_columns', 10, 2 );
    function sv_wc_csv_export_reorder_columns( $column_headers, $csv_generator ) {
        // Save "column_1" in a new array
        $column1 = array('column_1' => __("Contact Name") );
        // Remove "column_1" to be reordered
        unset( $column_headers['column_1'] );
        // Remove unnecessary "delivery_date"
        unset( $column_headers['delivery_date'] );
    
        // Set "column_1" as first column merging arrays
        return $column1 + $column_headers;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.