如何在自定义插件中使用自有模板发送WooCommerce风格邮件?
问题描述
我想在自定义插件里发送带有标准WooCommerce布局的邮件,并且希望使用存放在自己插件目录内的自定义邮件模板。目前当我把模板移到/wp-content/plugins/woocommerce/templates/emails目录时,下面的代码能正常运行,但我想把模板放在自己的插件里,推测需要在get_custom_email_html()里添加模板路径,但不知道具体怎么操作。
现有可正常运行的代码:
function get_custom_email_html( $heading = false, $mailer ) { $template = 'emails/my-custom-email-i-want-to-send.php'; return wc_get_template_html( $template, array( 'email_heading' => $heading, 'sent_to_admin' => false, 'plain_text' => false, 'email' => $mailer ) ); } // load the mailer class $mailer = WC()->mailer(); //format the email $recipient = "someone@somewhere.com"; $subject = __("Hi! Here is a custom notification from us!", 'theme_name'); $content = get_custom_email_html( $subject, $mailer ); $headers = "Content-Type: text/html "; //send the email through wordpress $mailer->send( $recipient, $subject, $content, $headers );
我的自定义模板代码:
/* * @hooked WC_Emails::email_header() Output the email header */ do_action( 'woocommerce_email_header', $email_heading, $email ); ?> <p><?php esc_html_e( 'This a test', 'my-plugin' ); ?></p> <?php /* * @hooked WC_Emails::email_footer() Output the email footer */ do_action( 'woocommerce_email_footer', $email );
解决方案
要让WooCommerce识别你插件内的自定义模板,只需给wc_get_template_html()添加自定义模板路径,具体步骤如下:
在你的插件目录内创建模板存放结构,比如:
你的插件根目录/templates/emails/my-custom-email-i-want-to-send.php修改
get_custom_email_html()函数,在调用wc_get_template_html时传入你的插件模板路径:
function get_custom_email_html( $heading = false, $mailer ) { // 定义插件模板根目录路径 $plugin_template_root = untrailingslashit( plugin_dir_path( __FILE__ ) ) . '/templates/'; $template = 'emails/my-custom-email-i-want-to-send.php'; return wc_get_template_html( $template, array( 'email_heading' => $heading, 'sent_to_admin' => false, 'plain_text' => false, 'email' => $mailer ), '', // 子目录参数留空 $plugin_template_root // 传入插件模板根目录 ); }
说明
wc_get_template_html()的第四个参数是模板文件的基础查找路径,默认优先检查主题下的WooCommerce模板,再检查WooCommerce插件自带模板。传入你自己的插件路径后,WooCommerce会优先查找这个路径下的模板。plugin_dir_path(__FILE__)会获取当前代码文件所在的插件目录路径,结合你创建的/templates/子目录,就能准确定位到自定义邮件模板。
- 保持邮件发送的其余代码不变,现在你的模板就可以放在自己的插件目录内正常调用了。
内容的提问来源于stack exchange,提问作者Vlado
相关产品推荐
相关产品推荐

