基于自定义字段值的不同 WooCommerce 电子邮件标题

时间:2021-04-06 13:34:17

标签: php email templates woocommerce email-notifications

我正在尝试根据订单自定义字段“交货类型”更改我的电子邮件标头,以帮助商店的员工确定订单是用于交货还是取货,他们希望对电子邮件标头进行颜色编码。

这里有几篇有用的帖子解释了如何解除 WooCommerce 电子邮件标头的绑定,然后有效地在每个电子邮件模板(新订单、处理等)中手动将调用添加到 email-header.php 模板或使用 switch 语句根据电子邮件类型应用新标题。

我正在尝试根据一些自定义订单元数据自定义 email-header.php 模板,用于新订单电子邮件通知。

目前我在 admin-new-order.php 模板中执行此操作,但是由于您必须全局取消设置/取消绑定标头,因此您必须为每个模板手动添加对 email-header.php 模板的调用邮件类型/模板。

基于 Woocommerce different headers for each email types 答案代码,这是我的代码尝试:

add_action( 'init', 'replace_email_header_hook' );

function replace_email_header_hook(){
    remove_action( 'woocommerce_email_header', array( WC()->mailer(), 'email_header' ) );
    add_action( 'woocommerce_email_header', 'woocommerce_email_header', 10, 2 );
}

function woocommerce_email_header( $email_heading, $email ) {

    $order = $email->object;

    $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;

    $del_type = get_post_meta( $order_id, 'delivery_type', true );

    switch($email->id) {
    case 'new_order':
        if ($del_type == 'delivery') {

            $template = 'emails/email-header-alt.php';

        }

        else if ($del_type == 'pickup') {


                $template = 'emails/email-header.php';


            }
        break;
    default:
        $template = 'emails/email-header.php';
    }
    wc_get_template( $template, array( 'email_heading' => $email_heading ) );
}

问题似乎与 $order_id 变量有关,当试图从该钩子内的 Order 对象中获取它时,我不确定这是否可行。

1 个答案:

答案 0 :(得分:2)

您代码中的主要错误是 else if,它应该是 elseif,您应该以不同的方式重命名您的自定义函数 woocommerce_email_header

$email->object 没有问题,它是 WC_Order 对象。如果需要,您可以使用 $email->object->get_id() 5 获取订单 ID。

从 WooCommerce 3 开始,您的代码也可以得到简化和优化。请尝试以下操作:

add_action( 'init', 'customizing_woocommerce_email_header' );
function customizing_woocommerce_email_header(){
    remove_action( 'woocommerce_email_header', array( WC()->mailer(), 'email_header' ) );
    add_action( 'woocommerce_email_header', 'custom_email_header', 10, 2 );
}

function custom_email_header( $email_heading, $email ) {
    $template = 'email-header.php'; // Default template

    if ( 'new_order' === $email->id && 'delivery' === $email->object->get_meta( 'delivery_type' ) ) {
        $template = 'email-header-alt.php'; // Custom template
    }
    wc_get_template( 'emails/'.$template, array( 'email_heading' => $email_heading ) );
}

代码位于活动子主题(或活动主题)的functions.php 文件中。经测试有效。