Home > Software design >  How to pass "$email" to WooCommerce emails template files if not available by default
How to pass "$email" to WooCommerce emails template files if not available by default

Time:05-06

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?

CodePudding user response:

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_data'] = array(
        'email_id'  => $email->id, // The email ID (to target specific email notification)
        'is_email'  => true // When it concerns a WooCommerce email notification
    );
} 
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:

// Getting the custom 'email_data' global variable
$ref_name_globals_var = $GLOBALS;

// Isset & NOT empty
if ( isset ( $ref_name_globals_var ) && ! empty( $ref_name_globals_var ) ) {
    // Isset
    $email_data = isset( $ref_name_globals_var['email_data'] ) ? $ref_name_globals_var['email_data'] : '';
    
    // NOT empty
    if ( ! empty( $email_data ) ) {
        // Targeting specific email notifications - multiple statuses can be added, separated by a comma
        if ( in_array( $email_data['email_id'], array( 'new_order', 'customer_processing_order' ) ) ) {
            // Desired output
            echo '<img alt="order in processing" src="https/example.com/image.png" />';
        }
    }
}
  • Related