Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FrancoStino/c30751bfd1fb33e5ea5587c12d0a5df8 to your computer and use it in GitHub Desktop.
Save FrancoStino/c30751bfd1fb33e5ea5587c12d0a5df8 to your computer and use it in GitHub Desktop.
Export customers who have placed orders in a CSV file
<?php
/*
* Esporta i clienti che hanno effettuato gli ordini in un file CSV
*/
function export_customers_to_csv() {
ob_end_clean();
ob_start();
global $wpdb;
$query = "
SELECT DISTINCT meta_value
FROM {$wpdb->prefix}postmeta
WHERE meta_key = '_customer_user'
";
$customer_ids = $wpdb->get_results($query, ARRAY_A);
$headers = array(
'ID Cliente',
'Nome',
'Cognome',
'Email',
'Telefono',
'Indirizzo',
'Città',
'Provincia',
'CAP',
'Ordini'
);
$data = array($headers);
foreach ($customer_ids as $customer_id) {
$customer = new WC_Customer($customer_id['meta_value']);
$orders = wc_get_orders(array(
'customer' => $customer->get_id()
));
if (count($orders) > 0) {
$customer_data = array(
$customer->get_id(),
$customer->get_first_name(),
$customer->get_last_name(),
$customer->get_email(),
$customer->get_billing_phone(),
$customer->get_billing_address_1(),
$customer->get_billing_city(),
$customer->get_billing_state(),
$customer->get_billing_postcode(),
implode(", ", array_map(function($order) { return $order->get_id(); }, $orders))
);
$data[] = $customer_data;
}
}
$filename = 'clienti_'.date('Ymd').'.csv';
header('Content-Type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename=\"$filename\"");
$output = fopen('php://output', 'w');
foreach ($data as $row) {
fputcsv($output, $row, ';');
}
ob_end_flush();
exit();
}
/*
* Crea una voce nel menu nella sezione Woocommerce per esportare i clienti
*/
function register_customers_csv_export_menu() {
add_submenu_page(
'woocommerce',
'Esporta clienti',
'Esporta clienti',
'manage_woocommerce',
'export-customers',
'export_customers_to_csv'
);
}
add_action( 'admin_menu', 'register_customers_csv_export_menu' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment