Export Selected Orders to CSV
Adds an "Export to CSV" bulk action to the admin orders list that downloads the selected orders with customer, address, items and totals for spreadsheets or accounting.
Opens WPIDE on
Code
$wpide_export_action = function ( $actions ) {
$actions['wpide_export_csv'] = 'Export to CSV';
return $actions;
};
add_filter( 'bulk_actions-woocommerce_page_wc-orders', $wpide_export_action, 30 );
add_filter( 'bulk_actions-edit-shop_order', $wpide_export_action, 30 );
$wpide_export_handle = function ( $redirect, $action, $ids ) {
if ( 'wpide_export_csv' !== $action || ! current_user_can( 'edit_shop_orders' ) ) {
return $redirect;
}
$cell = function ( $value ) {
$value = (string) $value;
return preg_match( '/^[=+\-@\t\r]/', $value ) ? "'" . $value : $value;
};
nocache_headers();
header( 'Content-Type: text/csv; charset=utf-8' );
header( 'Content-Disposition: attachment; filename=orders-' . gmdate( 'Y-m-d-His' ) . '.csv' );
$out = fopen( 'php://output', 'w' );
fwrite( $out, "\xEF\xBB\xBF" ); // UTF-8 BOM for Excel.
fputcsv( $out, array( 'Order', 'Date', 'Status', 'First name', 'Last name', 'Email', 'Phone', 'Company', 'Address', 'City', 'Postcode', 'Country', 'Items', 'Shipping', 'Discount', 'Tax', 'Total', 'Currency', 'Payment method' ) );
foreach ( array_map( 'absint', (array) $ids ) as $id ) {
$order = wc_get_order( $id );
if ( ! $order ) {
continue;
}
$items = array();
foreach ( $order->get_items() as $item ) {
$items[] = $item->get_quantity() . ' x ' . $item->get_name();
}
fputcsv( $out, array_map( $cell, array(
$order->get_order_number(),
$order->get_date_created() ? $order->get_date_created()->date_i18n( 'Y-m-d H:i' ) : '',
wc_get_order_status_name( $order->get_status() ),
$order->get_billing_first_name(),
$order->get_billing_last_name(),
$order->get_billing_email(),
$order->get_billing_phone(),
$order->get_billing_company(),
trim( $order->get_billing_address_1() . ' ' . $order->get_billing_address_2() ),
$order->get_billing_city(),
$order->get_billing_postcode(),
$order->get_billing_country(),
implode( '; ', $items ),
$order->get_shipping_total(),
$order->get_discount_total(),
$order->get_total_tax(),
$order->get_total(),
$order->get_currency(),
$order->get_payment_method_title(),
) ) );
}
fclose( $out );
exit;
};
add_filter( 'handle_bulk_actions-woocommerce_page_wc-orders', $wpide_export_handle, 10, 3 );
add_filter( 'handle_bulk_actions-edit-shop_order', $wpide_export_handle, 10, 3 );
Notes
Values starting with =, +, - or @ are prefixed with an apostrophe so spreadsheets do not run them as formulas.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.