phptemplateswoocommerceordersemail-notifications

Get the order object in Woocommerce email-header template


I am trying to fetch order items in WooCommerce email header for some conditional content in emails/email-header.php Woocommerce template file

I have tried to print_r the $order but it's empty and not giving any results.

Any help is appreciated.


Solution

  • Update:

    Since WooCommerce 3.7, the $email variable is now included and accessible via global, so to get the order object you can use:

    <?php
        global $email;
        
        $order = $email->object;
    ?>
    

    The way to get the $order object, is to include the $email global variable back in the template (as it should be, like in the related hooked function):

    add_action( 'woocommerce_email_header', 'email_header_before', 1, 2 );
    function email_header_before( $email_heading, $email ){
        $GLOBALS['email'] = $email;
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works

    Once done and saved, in your template emails/email-header.php you will insert the following at the beginning:

    <?php
        // Call the global WC_Email object
        global $email; 
    
        // Get an instance of the WC_Order object
        $order = $email->object; 
    ?>
    

    So know you can use the WC_Order object $order anywhere on the template like:

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

    or 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();
        } 
    ?>
    

    Tested and works