在 Woocommerce email-header 模板中获取订单 object

Get the order object in Woocommerce email-header template

我正在尝试在 WooCommerce 电子邮件 header 中获取订单项,以获取 emails/email-header.php Woocommerce 模板文件中的某些条件内容

我已经尝试 print_r $order 但它是空的,没有给出任何结果。

感谢任何帮助。

获取 **$order** 对象的方法是将 $email 全局变量包含在模板中(它应该是这样的,就像在相关的钩子函数):

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

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效

一旦完成保存,在您的模板emails/email-header.php中,您将在开头:

<?php
    // Call the global WC_Email object
    global $email; 

    // Get an instance of the WC_Order object
    $order = $email->object; 
?>

所以知道您可以在模板的任何位置使用 WC_Order 对象 $order,例如:

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

或获取订单商品:

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

经过测试并有效