Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 39 ยท Emails, Notifications and Admin

Custom Transactional Emails

Create a custom WooCommerce transactional email: extend WC_Email, register it, trigger it, write HTML and plain templates, use placeholders and test it locally.

WooCommerce sends many emails on its own: new order, processing order, completed order, refunds, password resets. Each one is an object with a subject, a heading, a recipient, two templates (HTML and plain text) and a settings screen where the shop owner can edit them. When your extension needs to tell somebody something ("your gift note was added", "a delivery slot is running out"), you should not call wp_mail() directly. A custom WC_Email class gives you the same settings screen, the same branded layout, theme overrides and plain-text support for free.

This lesson builds the anatomy of a custom email, shows the trigger, the templates and the placeholders, explains how to test mail locally, and then practices the template logic in runnable plain PHP. The real classes need WordPress and WooCommerce, so they are read-only. The order data you pass in comes from the CRUD layer; see Orders and High-Performance Order Storage. For the product-design side of messages, see Email and the Order Lifecycle.

How an email is sent

flowchart LR
    A["do_action(acme_gift_note, order_id)"] --> B["WC_Emails loads all registered emails"]
    B --> C["trigger() on your class"]
    C --> D{"Enabled and has recipient?"}
    D -- yes --> E["get_content(): render template"]
    E --> F["send(): wp_mail with headers"]
    D -- no --> G["Nothing happens"]

Your class decides whether to send; WooCommerce supplies the settings, layout and delivery.

WooCommerce keeps all email classes in the WC_Emails object (WC()->mailer()). It creates that object lazily, so a custom hook has to tell WooCommerce that it should wake the mailer when your action fires. You do that by adding the action name to the woocommerce_email_actions filter, which is what the built-in emails use too.

The email class

Read-only skeleton:

PHP
<?php
class Acme_Email_Gift_Note extends WC_Email {

    public function __construct() {
        $this->id             = 'acme_gift_note';
        $this->customer_email = true;
        $this->title          = __( 'Gift note added', 'acme' );
        $this->description    = __( 'Sent to the customer when a gift note is added to an order.', 'acme' );

        $this->template_base  = ACME_PLUGIN_DIR . 'templates/';
        $this->template_html  = 'emails/acme-gift-note.php';
        $this->template_plain = 'emails/plain/acme-gift-note.php';

        $this->placeholders = [
            '{order_number}' => '',
            '{order_date}'   => '',
        ];

        add_action( 'acme_gift_note_notification', [ $this, 'trigger' ], 10, 2 );

        parent::__construct();
    }

    public function get_default_subject(): string {
        return __( 'A gift note was added to order {order_number}', 'acme' );
    }

    public function get_default_heading(): string {
        return __( 'Your gift note', 'acme' );
    }

    public function trigger( $order_id, $order = false ): void {
        $this->setup_locale();

        if ( $order_id && ! is_a( $order, 'WC_Order' ) ) {
            $order = wc_get_order( $order_id );
        }

        if ( is_a( $order, 'WC_Order' ) ) {
            $this->object                         = $order;
            $this->recipient                      = $order->get_billing_email();
            $this->placeholders['{order_number}'] = $order->get_order_number();
            $this->placeholders['{order_date}']   = wc_format_datetime( $order->get_date_created() );
        }

        if ( $this->is_enabled() && $this->get_recipient() ) {
            $this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
        }

        $this->restore_locale();
    }

    public function get_content_html(): string {
        return wc_get_template_html( $this->template_html, [
            'order'              => $this->object,
            'email_heading'      => $this->get_heading(),
            'additional_content' => $this->get_additional_content(),
            'sent_to_admin'      => false,
            'plain_text'         => false,
            'email'              => $this,
        ], '', $this->template_base );
    }

    public function get_content_plain(): string {
        return wc_get_template_html( $this->template_plain, [
            'order'              => $this->object,
            'email_heading'      => $this->get_heading(),
            'additional_content' => $this->get_additional_content(),
            'sent_to_admin'      => false,
            'plain_text'         => true,
            'email'              => $this,
        ], '', $this->template_base );
    }
}

Then register the class and the action:

PHP
<?php
add_filter( 'woocommerce_email_classes', function ( array $emails ): array {
    $emails['Acme_Email_Gift_Note'] = new Acme_Email_Gift_Note();
    return $emails;
} );

add_filter( 'woocommerce_email_actions', function ( array $actions ): array {
    $actions[] = 'acme_gift_note';
    return $actions;
} );

// Later, when the gift note has been saved:
do_action( 'acme_gift_note', $order->get_id(), $order );

What each piece does:

  • $id is the key used in option names and in the admin URL. Keep it stable.
  • $customer_email = true marks the email as customer-facing. For admin emails the recipient is a setting and trigger() normally leaves $this->recipient as configured.
  • $placeholders is an array of keys. get_subject(), get_heading() and get_additional_content() run the saved text through format_string(), which replaces the tokens. You refill the values each time in trigger(), because one object can send many emails in a request.
  • parent::__construct() loads the settings and adds the standard fields: enable/disable, subject, heading, additional content and email type (plain text, HTML or multipart). It must run after you set $id and the template properties.
  • setup_locale() and restore_locale() switch to the recipient's language while the email is built, so translations match the customer.
  • get_content() picks HTML or plain text depending on the email type setting; you implement both get_content_html() and get_content_plain().

The templates

A template is an ordinary PHP file that prints the body, and WooCommerce wraps it with the shared header and footer. Here is a read-only HTML template; the plain-text one is the same idea without markup:

PHP
<?php
defined( 'ABSPATH' ) || exit;

do_action( 'woocommerce_email_header', $email_heading, $email );
?>

<p><?php printf( esc_html__( 'Hi %s,', 'acme' ), esc_html( $order->get_billing_first_name() ) ); ?></p>

<p><?php echo esc_html( $order->get_meta( '_acme_gift_note' ) ); ?></p>

<?php
if ( $additional_content ) {
    echo wp_kses_post( wpautop( wptexturize( $additional_content ) ) );
}

do_action( 'woocommerce_email_footer', $email );

Three rules apply here, just as in every template:

  1. Escape on output. Names and notes come from shoppers; esc_html() protects HTML emails from injected markup. In plain-text templates use wp_strip_all_tags() instead.
  2. Use the shared hooks (woocommerce_email_header, woocommerce_email_footer) so store branding applies.
  3. Make them overridable. Because you load templates with wc_get_template_html(), a theme can copy yours to yourtheme/woocommerce/emails/acme-gift-note.php. The lookup works as described in Template Overrides and Plugin Templates.

Settings in admin

Once registered, the email appears under WooCommerce > Settings > Emails, where a store owner can enable it, change the subject and heading (using your placeholders), add extra content and choose HTML or plain text. You get that screen without writing form code. If you need an extra field (for example "Copy to"), override init_form_fields(), call parent::init_form_fields() first and append your field; the field format is the same as in Adding Settings Pages and Tabs.

Testing locally

A development site must never send real mail to real customers. Use a mail catcher such as Mailpit or MailHog, or a plugin that logs outgoing mail, and point WordPress at it. Then:

  • Trigger your action from a test order and open the captured message to check the HTML and the plain-text part.
  • Check the subject and heading after changing them in the settings: placeholders that stay as mean you forgot to fill them in trigger().
  • Test with the email type set to plain text and to multipart.
  • Check that a disabled email sends nothing.
  • Run it from a queue or a webhook handler too: when no web request is in flight, WC()->mailer() still works, but remember that $_SERVER values may be missing.

Sending mail inside a checkout request slows the page and fails loudly when the mail server is slow. For anything heavy, schedule the do_action with the tools from Background Processing With Action Scheduler.

A template renderer you can run

The stand-in implements the logic that matters: replacing , keeping unknown tokens visible so mistakes are easy to spot, escaping values for HTML and stripping them for plain text. It is not WooCommerce: there is no layout, no settings table and no wp_mail().

PHP Placeholder renderer for HTML and plain text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Look at the HTML line: the tags inside the customer name were turned into text, so they cannot inject markup. In the plain version they are removed. The unknown stays in the output, which is the visual hint that something was not filled.

A tiny email class you can run

This second stand-in models the lifecycle of the real class: settings, enabled check, recipient check, subject override and a fake "send" that records messages.

PHP Stand-in email class: enable, recipient and subject

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use a WC_Email subclass instead of calling wp_mail() directly?

    WC_Email adds the standard enable, subject, heading and type settings, wraps content in the store layout and lets themes override your templates.
  2. 2. Where should placeholder values such as {order_number} be filled in?

    One email object can send several emails in a request, so the values must be set from the current order each time trigger() runs.
  3. 3. What do you register with the woocommerce_email_classes filter?

    The filter collects the email objects that WC_Emails manages, which is also how they appear in the settings screen.
  4. 4. Which output function belongs in an HTML email template for a customer-supplied note?

    Shopper input must be escaped when printed so it cannot inject markup or scripts into the message.

Summary

  • A custom email extends WC_Email, sets id, title, templates and placeholders, and calls parent::__construct().
  • Register it with woocommerce_email_classes and add your trigger action to woocommerce_email_actions so the mailer loads in time.
  • trigger() fills the object and placeholders, checks is_enabled() and the recipient, then calls send().
  • Provide HTML and plain-text templates, escape output and let themes override them.
  • Test with a mail catcher, in HTML, plain and multipart modes, and move slow sending out of the checkout request.

Next: Admin Order Screens and Analytics Data