在后端获取WooCommerce电子邮件类

时间:2018-08-27 作者:melvin

如何在WordPress管理页面中获取所有可用的WooCommerce电子邮件类。我想上所有的课(WC_Email_New_Order, WC_Email_Cancelled_Order) 等等,我试过了woocommerce_email_classes 筛选,但我无法获取类。

更新我添加了以下内容

add_filter( \'woocommerce_email_classes\', \'my_email_classes\', 10, 1);

function my_email_classes( $emails ){
    $mailer = WC()->mailer();
    $mails = $mailer->get_emails();

    $mails[\'WC_Email_Cancelled_Order\']->template_html = MY_TEMPLATE_PATH.\'test.php\';

    return $mails;
}

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

正如我在评论中指出的,您可以使用wc()->mailer()->emails, 这会给你一个所有电子邮件的列表class 实例。示例:

// Get all the email class instances.
$emails = wc()->mailer()->emails;

// Prints all the email class names.
var_dump( array_keys( $emails ) );

// Access the default subject for new order email notifications.
$subject = $emails[\'WC_Email_New_Order\']->get_default_subject();
也可以从连接到的回调函数中访问相同的“$电子邮件”woocommerce_email_classes 滤器下面是重写特定类的示例:

// By default, $emails is an array of \'{CLASS NAME}\' => {The class instance}.
add_filter( \'woocommerce_email_classes\', function( $emails ){
    $emails[\'WC_Email_New_Order\'] = include \'path/to/your/custom/class.php\';
    /* Or if the class file is already "included":
    $emails[\'WC_Email_New_Order\'] = new My_Custom_WC_Email_New_Order_Class();
    */

    return $emails;
} );
以及(尽管您可能已经知道)电子邮件class 文件(例如。class-wc-email-new-order.php) 存储在woocommerce/includes/emails.

访问emails 属性(或class 实例)使用wc()->mailer()->get_emails(), 除了从连接到woocommerce_email_classes 过滤器

// Both of these work, but the latter is preferred.
$emails = wc()->mailer()->emails;
$emails = wc()->mailer()->get_emails();
附加代码(These are in reply to your comments as well as the "UPDATE" part in your question.)

我可以使用$emails[\'WC_Email_New_Order\']->template_html 强制自定义模板选择?

是的,你可以。但是,该值需要是相对于主题中自定义WooCommerce模板目录的路径;e、 g。wp-content/themes/your-theme/woocommerce. 因此:

// This works, if wp-content/themes/your-theme/woocommerce/emails/your-custom-template.php
// exists.
$emails[\'WC_Email_New_Order\']->template_html = \'emails/your-custom-template.php\';

// But this doesn\'t work, even if the file exists.
$emails[\'WC_Email_New_Order\']->template_html = \'/absolute/path/to/your-custom-template.php\';
如果要使用绝对路径(例如在自定义插件文件夹中),可以使用woocommerce_locate_core_template 过滤器:

// $a and $b can be ignored, but $file and $id are important
add_filter( \'woocommerce_locate_core_template\', function( $file, $a, $b, $id ){
    if ( \'new_order\' === $id ) {
        return \'/absolute/path/to/your-custom-template.php\';
    }

    return $file;
}, 10, 4 );

结束

相关推荐