Get the order object in Woocommerce email-header template

To access the $order object in your WooCommerce email-header template, follow these steps:

1. Add the following code to your theme’s ‘functions.php’ file:

add_action('woocommerce_email_header', 'email_header_before', 1, 2);

function email_header_before($email_heading, $email) {

    $GLOBALS['email'] = $email;

}

This action hook ensures that the global $email variable is available in your template.

2. In your ’emails/email-header.php’ template file, include the following code at the beginning:

<?php

    // Call the global WC_Email object

    global $email;

    // Get an instance of the WC_Order object

    $order = $email->object;

?>

Now, you can utilize the $order object throughout the template.

For example, to display the billing city, use:

<?php echo __('City: ') . $order->get_billing_city(); ?> // display the billing city ?>

And to fetch order items:

<?php

    // Loop through order items

    foreach ($order->get_items() as $item_id => $item) {

        // Get the product ID

        $product_id = $item->get_product_id();

        // Get the product (an instance of the WC_Product object)

        $product = $item->get_product();

    }

?>
Scroll to Top