上一篇文章介绍了如何在WooCommerce中添加自定义邮件,提到了一个问题就是如何使用自己的模板。Email模板默认放在插件的templates/emails目录下,可以通过在主题的woocommerce/emails目录下放置同名文件覆盖,今天我们也模仿一下这个机制,把自定义的模板放在主题(或插件)某个目录下,可以用同样方式覆盖。
使用自定义模板要更改两个地方,请参照上一篇文章里提到的class-wc-email-new-order.php代码对比一下。
目录
更改一,定义自己的email class时声明默认模板路径
更改之前是这样
$this->template_html = 'emails/admin-new-order.php'; $this->template_plain = 'emails/plain/admin-new-order.php';
更改以后变成这样
$this->template_base = untrailingslashit( dirname( __FILE__ ) ) . '/emails/'; $this->template_html = 'admin-custom-order.php'; $this->template_plain = 'plain/admin-custom-order.php';
注意template_base的定义以及新的模板文件admin-custom-order.php。
在class-wc-email-new-order.php所在目录创建一个emails文件夹放置这两个文件。
这样做的效果马上可以体现出来,如下图所示,copy的源文件路径已经变成主题目录了。
更改二:wc_get_template()函数的默认路径
wc_get_template()的函数原型是
function wc_get_template( $template_name, $args = array(), $template_path = '', $default_path = '' )
$default_path默认是woocommerce插件下的目录,需要改成我们自定义的目录,class文件里所有使用wc_get_template()的地方都要改,比如:
function get_content_html() { ob_start(); wc_get_template( $this->template_html, array( 'order' => $this->object, 'email_heading' => $this->get_heading(), 'sent_to_admin' => true, 'plain_text' => false ) ); return ob_get_clean(); }
要改成
function get_content_html() { ob_start(); wc_get_template( $this->template_html, array( 'order' => $this->object, 'email_heading' => $this->get_heading(), 'sent_to_admin' => true, 'plain_text' => false ), '', $this->template_base ); return ob_get_clean(); }
WooCommerce自定义邮件模测试
admin-custom-order.php的内容直接拷贝admin-new-order.php的内容,再添加一点文字证明模板不同。找一个订单,使用重发邮件的功能测试,可以发现已经在使用自定义模板了。
因为我的发货操作是发送一封邮件,包含购买者的账号。
这步骤我总是使用 QQ 企业邮箱,登陆后,粘贴 HTML 代码,接着换到可视化模式,手动输入对方的账号和密码。很麻烦。
能否通过这个,使用 WordPress 的发送功能,每次输入自定义的一个账户密码,然后使用 PHP 发送出去呢?这样会很方便。可以开发一个插件吗,可以选择购买者(自动填充他的邮箱地址),输入每次不同的那个部分,其他地方样式一样,然后发送。那样我会买。
还有就是,没找到哪个插件是像编写邮件那样的,可以发给特定的人。其实就是自建邮局的感觉。每次都要登陆 QQ 企业邮箱,因为只有它才支持 HTML 代码。好麻烦啊。