With this code snippet you can attach PDF files to e-mail plain and simply
But that was not good enough for me!
So I added this code with a little help from ChatGPT 🙂
First I wanted this only to fire up when the order is completed in WooCommerce. I did that with 'customer_completed_order' which is a standard WooCommerce Hook
After that I asked if they could make it with multiple PDF files. And also with custom category.
Here is what we ended up with - me and the mighty GPT, after several tries.
Example:
'sanketure' is a product category and sanketur.pdf is the PDF we want to send, if customer is buying something from that category.
And then it continues with 'oesters-safari' and 'svampeture'
add_filter('woocommerce_email_attachments', 'custom_attach_pdf_to_emails', 10, 4);
function custom_attach_pdf_to_emails($attachments, $email_id, $order, $email) {
// Check if the email is customer completed order
if ($email_id === 'customer_completed_order') {
$upload_dir = wp_upload_dir();
// Define the product category slugs and their corresponding PDF files
$category_to_pdf = array(
'sanketure' => 'sanketur.pdf',
'oesters-safari' => 'osterssafari.pdf',
'svampeture' => 'svampetur.pdf',
);
// Get the product categories for the order
$product_categories = array();
foreach ($order->get_items() as $item_id => $item) {
$product_id = $item->get_product_id();
$terms = get_the_terms($product_id, 'product_cat');
if ($terms && !is_wp_error($terms)) {
foreach ($terms as $term) {
$product_categories[] = $term->slug;
}
}
}
// Check if any of the product categories match the desired ones
foreach ($product_categories as $category) {
if (isset($category_to_pdf[$category])) {
// Attach the corresponding PDF file
$attachments[] = $upload_dir['basedir'] . "/2023/12/" . $category_to_pdf[$category];
}
}
}
return $attachments;
}
Liked this article? Please follow me on TwitterFollow @baysorensen