Ship your own email templates from an add-on
An add-on that sends mail through Benecaster needs somewhere to keep its own templates. Register the directory once, on benecaster_boot, against the EmailRenderer the container gives you: that is the instance Benecaster sends with.
The directory is the template root itself, so templates/emails/my-addon-receipt.php is the template my-addon-receipt. Translations go in a subdirectory named for the locale: templates/emails/fr_FR/my-addon-receipt.php.
Benecaster looks for a template in the child theme, then the parent theme, then its own templates/emails/, then your directory, trying every locale-specific location before any unlocalised one. Both ends of that order matter:
- A theme beats your directory. A podcaster can override your email from their theme
exactly as they override Benecaster’s, at{theme}/benecaster/emails/{template}.php. - Benecaster beats your directory. You cannot replace a Benecaster email by shipping a
file with the same name; awelcome.phpin your directory is never reached. To change a Benecaster email, filterbenecaster_email_body_html_{$type}, or have the podcaster override it in their theme. - Name your templates after your add-on. A generic name collides with Benecaster’s and
silently does nothing. - This is a different call from
benecaster_register_template_directory(). That one
registers front-end templates. An add-on that ships both registers each directory with its own function. - Registering is cheap and safe. No filesystem check is made, so a directory that does
not exist never matches, and registering the same one twice has no effect. - A missing template loses the whole message. When no file matches, nothing is
rendered, including the branded wrapper and the business address in the footer. - Older Benecaster has no
add_template_dir(). The method returns nothing and does not
exist on a version older than the one that introduced it, so probe for it withmethod_exists()at boot, record the answer, and make whatever queues your mail refuse when it is false. Failing open sends blank mail — no body, wrapper or business address — to everyone you email. If you also hold back one of Benecaster’s own emails in favour of yours, gate that on the same answer, or the person gets neither.
Code
<?php
add_action(
'benecaster_boot',
function ( \Benecaster\Container $container ): void {
$container
->make( \Benecaster\Email\EmailRenderer::class )
->add_template_dir( MY_ADDON_DIR . 'templates/emails' );
}
);
Hooks Used
Need this built rather than just documented? See our services →