Last active
June 7, 2022 13:39
-
-
Save Muetze42/e42d827922380daf0cc256c3fec67e9f to your computer and use it in GitHub Desktop.
WooCommerce: Order as CSV and attach to emails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter('woocommerce_email_attachments', function ($attachments, $emailId, $order) { | |
/* @var WC_Order $order */ | |
$attachTo = [ | |
'new_order', | |
'customer_on_hold_order', | |
'customer_processing_order', | |
'customer_completed_order', | |
'customer_refunded_order', | |
'customer_partially_refunded_order', | |
'cancelled_order', | |
//'failed_order', | |
//'customer_reset_password', | |
//'customer_invoice', | |
//'customer_new_account', | |
//'customer_note', | |
]; | |
if (in_array($emailId, $attachTo)) { | |
//$data = $order->get_data(); | |
$items = $order->get_items(); | |
/** | |
* The CSV heading | |
*/ | |
$list[] = [ | |
'Material', | |
'x', | |
'y', | |
'z', | |
'Menge', | |
'Preis', | |
]; | |
foreach ($items as $item) { | |
/* | |
* Product Price: 35 | |
* Quantity: 2 | |
* | |
* $order->get_item_total($item) 35 | |
* $order->get_item_subtotal($item) 35.00 | |
* $order->get_line_total($item) 70 | |
* $order->get_line_subtotal($item) 70 | |
* */ | |
/* @var WC_Order_Item $item */ | |
$list[] = [ | |
$item->get_name(), | |
$item->get_meta('x'), | |
$item->get_meta('y'), | |
$item->get_meta('z'), | |
$item->get_quantity(), | |
$order->get_item_subtotal($item, true), | |
]; | |
} | |
$dir = __DIR__.'/data'; | |
if (!is_dir($dir)) { | |
wp_mkdir_p($dir); | |
} | |
$htaccessFile = $dir.'/.htaccess'; | |
if (!file_exists($htaccessFile)) { | |
file_put_contents($htaccessFile, "Order deny,allow\nDeny from all"); | |
} | |
$fileName = $dir.'/'.$order->get_id().'.csv'; | |
$file = fopen($fileName,'w'); | |
foreach ($list as $line) { | |
fputcsv($file, $line, ';'); | |
} | |
fclose($file); | |
$attachments[] = $fileName; | |
} | |
return $attachments; | |
}, 10, 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment