Build Custom WooCommerce Email Notifications from Scratch

Build custom WooCommerce email notifications

WooCommerce emails are built on the abstract WC_Email class. It renders the templates inside the standard WooCommerce header and footer, adds the settings page (enable, subject, heading, additional content, email type) under WooCommerce → Settings → Emails, replaces placeholders like {order_number}, and sends through wp_mail(). Every built-in email (new order, processing, completed, refunded) is such a class, registered with the woocommerce_email_classes filter, and a custom email works the same way.

Problem: A store marks orders “Shipped” when the courier picks them up, before they are completed. Customers should get an email at that moment, with the tracking number, and the shop owner should be able to edit its subject and heading like any other WooCommerce email.

Solution: Register a custom “Shipped” order status, write a WC_Email subclass that is triggered by that status, add the status to the list of email actions, and render the content from overridable templates.

The status

<?php
add_action( 'init', function () {
    register_post_status( 'wc-shipped', array(
        'label'                     => _x( 'Shipped', 'Order status', 'myplugin' ),
        'public'                    => false,
        'show_in_admin_all_list'    => true,
        'show_in_admin_status_list' => true,
        'label_count'               => _n_noop( 'Shipped <span class="count">(%s)</span>', 'Shipped <span class="count">(%s)</span>', 'myplugin' ),
    ) );
} );

add_filter( 'wc_order_statuses', function ( $statuses ) {
    $statuses['wc-shipped'] = _x( 'Shipped', 'Order status', 'myplugin' );
    return $statuses;
} );

Let the status trigger emails

WooCommerce emails do not listen to woocommerce_order_status_shipped directly. WooCommerce takes a list of actions, the woocommerce_email_actions filter, and for each of them fires a …_notification twin, which the email classes listen to (and which can be sent in the background). A custom status is not in that list, so add it:

<?php
add_filter( 'woocommerce_email_actions', function ( $actions ) {
    $actions[] = 'woocommerce_order_status_shipped';
    return $actions;
} );

Without this, woocommerce_order_status_shipped_notification never fires and the email is never sent.

The email class

The class extends WC_Email, which exists only after WooCommerce is loaded, so keep it in its own file (includes/class-wc-email-shipped.php) and include it inside the filter that registers it:

<?php
// includes/class-wc-email-shipped.php
defined( 'ABSPATH' ) || exit;

class WC_Email_Shipped extends WC_Email {

    public function __construct() {
        $this->id             = 'customer_shipped_order';
        $this->customer_email = true;
        $this->title          = __( 'Shipped order', 'myplugin' );
        $this->description    = __( 'Sent to the customer when the order status changes to Shipped.', 'myplugin' );
        $this->template_html  = 'emails/customer-shipped-order.php';
        $this->template_plain = 'emails/plain/customer-shipped-order.php';
        $this->template_base  = MYPLUGIN_PATH . 'templates/';
        $this->placeholders   = array(
            '{order_date}'   => '',
            '{order_number}' => '',
        );

        add_action( 'woocommerce_order_status_shipped_notification', array( $this, 'trigger' ), 10, 2 );

        // After the properties: the parent loads the settings for this ID
        parent::__construct();
    }

    public function get_default_subject() {
        return __( 'Your {site_title} order #{order_number} has shipped', 'myplugin' );
    }

    public function get_default_heading() {
        return __( 'Your order is on its way', 'myplugin' );
    }

    public function trigger( $order_id, $order = false ) {
        $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_date}']   = wc_format_datetime( $order->get_date_created() );
            $this->placeholders['{order_number}'] = $order->get_order_number();
        }

        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() {
        return wc_get_template_html( $this->template_html, array(
            '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() {
        return wc_get_template_html( $this->template_plain, array(
            '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 );
    }
}

Register it:

<?php
define( 'MYPLUGIN_PATH', plugin_dir_path( __FILE__ ) );

add_filter( 'woocommerce_email_classes', function ( $emails ) {
    require_once MYPLUGIN_PATH . 'includes/class-wc-email-shipped.php';
    $emails['WC_Email_Shipped'] = new WC_Email_Shipped();
    return $emails;
} );

get_default_subject() and get_default_heading() are the defaults the owner sees in the settings and can override; {site_title}, {order_number} and {order_date} are replaced when the email is built.

The template

templates/emails/customer-shipped-order.php in the plugin. A theme can override it by copying it to yourtheme/woocommerce/emails/customer-shipped-order.php:

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

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

<p><?php printf( esc_html__( 'Hi %s,', 'myplugin' ), esc_html( $order->get_billing_first_name() ) ); ?></p>
<p><?php esc_html_e( 'Your order has been picked up by our courier and is on its way.', 'myplugin' ); ?></p>

<?php $tracking = $order->get_meta( '_courier_tracking_number' ); ?>
<?php if ( $tracking ) : ?>
    <p><strong><?php esc_html_e( 'Tracking number:', 'myplugin' ); ?></strong> <?php echo esc_html( $tracking ); ?></p>
<?php endif; ?>

<?php
do_action( 'woocommerce_email_order_details', $order, $sent_to_admin, $plain_text, $email );
do_action( 'woocommerce_email_order_meta', $order, $sent_to_admin, $plain_text, $email );
do_action( 'woocommerce_email_customer_details', $order, $sent_to_admin, $plain_text, $email );

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

do_action( 'woocommerce_email_footer', $email );

The four woocommerce_email_* actions print the standard order table, meta and addresses, so the email looks like the built-in ones. The plain-text template in emails/plain/ follows the same structure without HTML.

Send it

<?php
$order = wc_get_order( $order_id );
$order->update_meta_data( '_courier_tracking_number', $tracking_number );
$order->update_status( 'shipped', __( 'Picked up by the courier.', 'myplugin' ) );

update_status() saves the order and fires the status hooks, and through the email actions the new email. In WooCommerce → Settings → Emails the “Shipped order” email can be previewed and edited like the others.

NOTE: How the status hooks fit together is described in WooCommerce order status transitions. For HTML emails outside WooCommerce, the simpler approach in HTML email templates with wp_mail() is enough.