Yes, you can achieve this in Magento 2 by using an observer to modify the order confirmation email based on the products ordered. Here's a basic outline of the steps you would need to follow:
- Create an observer for the email_order_set_template_vars_before event.
- In the observer, check the products in the order to see if they match the specific product or product type you are interested in.
- If the products match, modify the email template variables to include the custom message you want to include in the email.
- If the products don't match, simply let the observer continue as normal and the standard confirmation email will be sent.
Here's an example implementation of the observer:
Create a new module and add the following code to your events.xml file:
<event name="email_order_set_template_vars_before">
<observer name="custom_order_confirmation_email" instance="Vendor\Module\Observer\CustomOrderConfirmationEmail" />
</event>
Create a new observer class at Vendor\Module\Observer\CustomOrderConfirmationEmail.php:
<?php
namespace Vendor\Module\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
class CustomOrderConfirmationEmail implements ObserverInterface
{
/**
* @param Observer $observer
*/
public function execute(Observer $observer)
{
// Get the order and the email template variables
$order = $observer->getData('order');
$transport = $observer->getData('transport');
$vars = $transport->getData('vars');
// Check if the order contains the specific product or product type
$containsSpecificProduct = false;
foreach ($order->getAllVisibleItems() as $item) {
// Replace "PRODUCT TYPE" and "PRODUCT SKU" with your own values
if ($item->getProductType() == "PRODUCT TYPE" || $item->getSku() == "PRODUCT SKU") {
$containsSpecificProduct = true;
break;
}
}
// If the order contains the specific product, add the custom message
if ($containsSpecificProduct) {
$vars['custom_message'] = "This is a custom message for orders that contain the specific product or product type.";
}
// Update the email template variables and return the observer
$transport->setData('vars', $vars);
return $this;
}
}
In the email template file for the order confirmation email (sales_email_order_template.xml), you can then include the custom message by using the {{var custom_message}} variable wherever you want the message to appear.
Note: Make sure to replace "PRODUCT TYPE" and "PRODUCT SKU" in the observer code with the actual product type or SKU that you want to trigger the custom email.