【问题标题】:Different WooCommerce Email Header based on custom field value基于自定义字段值的不同 WooCommerce 电子邮件标题
【发布时间】:2021-07-02 07:11:33
【问题描述】:

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

这里有几个有用的帖子解释了如何取消绑定 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 对象获取 $order_id 变量时,该问题似乎与该变量有关,我不确定这是否可行。

【问题讨论】:

    标签: php email templates woocommerce email-notifications


    【解决方案1】:

    您的代码中的主要错误是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 文件中。经过测试并且可以工作。

    【讨论】:

    • 所以现在出现了一些明显的错误,包括我不需要测试是否存在“提货”的错误,因为唯一会改变的模板是交付。
    猜你喜欢
    • 2018-02-25
    • 1970-01-01
    • 2018-01-07
    • 2022-01-26
    • 2022-10-05
    • 2019-04-23
    • 2017-06-11
    • 1970-01-01
    相关资源
    最近更新 更多