Woocommerce 每种电子邮件类型的不同标头

Sti*_*art 4 php email wordpress hook woocommerce

我使用 Woocommerce,我需要根据其类型更改电子邮件标题,以便“customer-new-account.php”、“customer-processing-order.php”、“admin-new-order.php”(等等)...他们必须有不同的标题。

我刚刚在我的子模板中复制了 woocommerce“电子邮件”文件夹,现在我需要知道如何更改代码。

任何帮助表示赞赏。;-) 提前致谢。

Zik*_*iki 6

我相信最干净的方法是取消绑定默认的电子邮件标题操作并进行自定义。如果您检查任何电子邮件模板,例如。 /woocommerce/templates/emails/admin-new-order.php,您将在顶部看到他们已经将电子邮件对象作为第二个参数传递给操作,只是默认的 WC 钩子不使用它:

 <?php do_action( 'woocommerce_email_header', $email_heading, $email ); ?>
Run Code Online (Sandbox Code Playgroud)

所以functions.php你可以这样做:

// replace default WC header action with a custom one
add_action( 'init', 'ml_replace_email_header_hook' );    
function ml_replace_email_header_hook(){
    remove_action( 'woocommerce_email_header', array( WC()->mailer(), 'email_header' ) );
    add_action( 'woocommerce_email_header', 'ml_woocommerce_email_header', 10, 2 );
}

// new function that will switch template based on email type
function ml_woocommerce_email_header( $email_heading, $email ) {
    // var_dump($email); die; // see what variables you have, $email->id contains type
    switch($email->id) {
        case 'new_order':
            $template = 'emails/email-header-new-order.php';
            break;
        default:
            $template = 'emails/email-header.php';
    }
    wc_get_template( $template, array( 'email_heading' => $email_heading ) );
}
Run Code Online (Sandbox Code Playgroud)

如果您不需要切换整个文件而只想对现有标题进行小的更改,则可以将电子邮件类型参数传递到模板中,只需将底部模板包含替换为:

wc_get_template( $template, array( 'email_heading' => $email_heading, 'email_id' => $email->id ) );
Run Code Online (Sandbox Code Playgroud)

然后在您的标题模板中将其用作$email_id,例如:

<?php if($email_id == 'new_order'): ?>
    <h2>Your custom subheader to appear on New Order notifications only</h2>
<?php endif ?>
Run Code Online (Sandbox Code Playgroud)