Sql query to download order report in woocommerce

Solution 1:

From my own blog post, this is the format for the SQL to extract information from an EAV style table layout.

$reportQuery = "
SELECT
  A.ID as order_id
, B.meta_value as b_first_name
, C.meta_value as b_last_name
, D.meta_value as b_address_1
, E.meta_value as b_address_2
, F.meta_value as b_country
, G.meta_value as b_state
, H.meta_value as b_city
, I.meta_value as b_postcode
, J.meta_value as b_user_id
, K.user_email as b_email

FROM wp_posts as A
LEFT JOIN wp_postmeta B 
  ON A.id = B.post_id AND B.meta_key = '_billing_first_name'

LEFT JOIN wp_postmeta C
  ON A.id = C.post_id AND C.meta_key = '_billing_last_name'

LEFT JOIN wp_postmeta D
  ON A.id = D.post_id AND D.meta_key = '_billing_address_1'

LEFT JOIN wp_postmeta E
  ON A.id = E.post_id AND E.meta_key = '_billing_address_2'

LEFT JOIN wp_postmeta F
  ON A.id = F.post_id AND F.meta_key = '_billing_country'

LEFT JOIN wp_postmeta G
  ON A.id = G.post_id AND G.meta_key = '_billing_state'

LEFT JOIN wp_postmeta H
  ON A.id = H.post_id AND H.meta_key = '_billing_city'

LEFT JOIN wp_postmeta I
  ON A.id = I.post_id AND I.meta_key = '_billing_postcode'

LEFT JOIN wp_postmeta J
  ON A.id = J.post_id AND J.meta_key = '_customer_user'

LEFT JOIN wp_users K
  ON J.meta_value = K.ID

WHERE A.post_type = 'shop_order'
AND   A.post_status = 'wc-completed';
AND   A.post_date_gmt >= DATE_SUB(NOW(), INTERVAL 1 DAY)
";

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=woocommerce-'.date('Y-m-d').'.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
$rows = mysql_query($reportQuery);

while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
fclose($output);