In Woocommerce, I have a custom email template (id = 'wc_course_order') that sends when a specific product (an online course) is purchased.
Below I use a hooked function that adds recipients based on order metadata from custom fields (i.e. "Student Email"). It's based on this thread answer.
How can I add these recipients as BCC and grab their "First Name" field and add that to the body of the email, especially given that two quantities of the course product may be purchased together with two different student names/emails?
The row output is:
"meta_data": [{"id": 652,
"key": "First Name - 1",
"value": "John"},
{"id": 653,
"key": "Last Name - 1",
"value": "Doe"},
{"id": 654,
"key": "Student Email - 1",
"value": "johndoe@example.com"}]
And then for an additional student registered in the same purchase, output would be "key": "First Name - 2", "value": "Jane", and "... - 3" etc.
I realize that it can be split in two questions:
- How do I grab their names in addition to the emails (which I already grabbed, see full function below)?
- How do I add their email addresses as BCC instead of appending the $recipients as regular "TO:"?
The full function that I am using:
add_filter( 'woocommerce_email_recipient_wc_course_order', 'student_email_notification', 10, 2 );
function student_email_notification( $recipient, $order) {
$student_emails = array();
$enroll_num = 0;
// Loop though Order IDs
foreach( $order->get_items() as $item_id => $item_data ){
$course_qty = $item_data->get_quantity();
$q = 1;
while ( $q <= $course_qty){
// Get the student email
$enroll_num++;
$student_email = wc_get_order_item_meta( $item_id, 'Student Email - '.$enroll_num, true );
if( ! empty($student_email) )
$student_emails[] = $student_email; // Add email to the array
$q++;
}
}
// If any student email exist we add it
if( count($student_emails) > 0 ){
// Remove duplicates (if there is any)
$student_emails = array_unique($student_emails);
// Add the emails to existing recipients
$recipient .= ',' . implode( ',', $student_emails );
}
return $recipient;
}
Can this all be done within functions.php
or should this be done in the separate email template file I have?
As 'wc_course_order' is a custom email notification ID that I can't really test it with it (so for testing purpose I have commented it, when testing the function myself)…
Using the same way than you to get the email, I suppose that I am getting the first and last name in the code below (but I am not absolutely sure)…
Now to add this emails as BCC, you will have to change of hook:
Code goes in function.php file of your active child theme (or active theme). Tested and works
(I can't really test your code at 100%, but it should work, I hope).
Related: How to get order ID in woocommerce_email_headers hook