Search code examples
wordpresswoocommerceparametersemail-notifications

How to pass "$email" to WooCommerce emails template files if not available by default


I've checked many threads on the platform. But there is no thread which explains how to use the conditional $email>id parameter straight into a template.

This is what I have in email-header.php:

<div style="width:600px;" id="template_header_image">
    <?php
    if ( $img = get_option( 'woocommerce_email_header_image' ) ) {
        echo '<p style="margin-top:0;"><img width="80%" height="auto" src="' . esc_url( $img ) . '" alt="' . get_bloginfo( 'name', 'display' ) . '" /></p>';
    }
    if( $email->id == 'customer_processing_order'  ) {
        echo '<img alt="order in processing" src="https/example.com/image.png" />';
}
?>                          
</div>

The src is an example. The if( $email->id == 'customer_processing_order' ) is not working.

It seems that parameter $email is not being picked up. I tried to call it with global $email; but this also does not work.

Any advice?


Solution

  • In /includes/class-wc-emails.php we see that only $email_heading is passed via wc_get_template()

    /**
     * Get the email header.
     *
     * @param mixed $email_heading Heading for the email.
     */
    public function email_header( $email_heading ) {
        wc_get_template( 'emails/email-header.php', array( 'email_heading' => $email_heading ) );
    }
    

    So to pass the $email->id we have to use a workaround, first we will make the variable global available.


    1) This can be done via different hooks but the woocommerce_email_header hook seems to be the most suitable in this specific case:

    // Header - set global variable
    function action_woocommerce_email_header( $email_heading, $email ) {
        $GLOBALS['email_id'] = $email->id;
    } 
    add_action( 'woocommerce_email_header', 'action_woocommerce_email_header', 10, 2 );
    

    Code goes in functions.php file of the active child theme (or active theme).

    2) Then in the desired template file you can use:

    2.1) put this just after if ( ! defined( 'ABSPATH' ) ) {..}

    // Getting the email ID global variable
    $ref_name_globals_var = isset( $GLOBALS ) ? $GLOBALS : '';
    $email_id = isset( $ref_name_globals_var['email_id'] ) ? $ref_name_globals_var['email_id'] : '';
    

    2.2) and at the desired location, towards the output

    // Targeting specific email. Multiple statuses can be added, separated by a comma
    if ( in_array( $email_id, array( 'new_order', 'customer_processing_order' ) ) ) {
        // Desired output
        echo '<p style="color: red; font-size: 20px;">Your output</p>';
    }