In this tutorial, I’ll show you how to add a custom variable for all email templates.
Transactional emails play a vital role in the operation and success of an eCommerce store.
In Magento 2, transactional emails are automated emails sent to customers in response to specific actions or events in the store. These emails are crucial for customer communication and enhancing the user experience by providing timely information regarding their transactions and interactions with the store. You can learn more about email templates and email variables here.
In this blog post, I’ll demonstrate how to create a custom variable to dynamically retrieve the current year. You can then incorporate this variable into any email template, such as the copyright section of the footer, eliminating the need for manual updates when the year changes.
How to add a custom variable for all email templates?
I assume you are familiar with how to create a custom module and created it.
Step 1: Create di.xml at app/code/Vendor/Module/etc and paste the below code to create a plugin of core function where all the variables are being initialized.
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Email\Model\AbstractTemplate">
<plugin name="name_of_plugin"
type="Vendor\Module\Plugin\CustomEmailVariable"/>
</type>
</config>
Step 2: Create CustomEmailVariable.php at app/code/Vendor/Module/Plugin and paste code as plugin implementation below:
<?php
namespace Vendor\Module\Plugin;
class CustomEmailVariable
{
/**
* @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
*/
protected $timezone;
/**
* Construct function
*
* @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
*/
public function __construct(
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
) {
$this->timezone = $timezone;
}
public function beforeGetProcessedTemplate(
\Magento\Email\Model\AbstractTemplate $subject,
array $variables = []
) {
$variables['current_year'] = $this->timezone->date()->format('Y');
return [$variables];
}
}
That’s it! You can now access the value of this variable in your email templates using the syntax {{var current_year}}.
Please let me know in the comment section below if you found this tutorial helpful or if it meets your specific requirements. Your feedback is valuable!