
在WooCommerce中,当需要根据特定事件(如订单状态变更)发送定制邮件时,通常会使用add_action钩子来触发自定义函数。为这些邮件添加附件是常见的需求,例如发送PDF格式的礼品券、发票或产品手册。然而,直接添加附件可能会遇到路径不正确或邮件器使用方式过时的问题。
核心挑战在于:
以下是为WooCommerce订单状态变更时发送自定义邮件并附带附件的正确实现方式。
<?php
/**
* 为WooCommerce订单完成邮件添加附件
* 当订单状态变为“已完成”且支付方式为“货到付款”时触发
*/
function action_woocommerce_order_status_changed_with_attachment( $order_id, $old_status, $new_status, $order ) {
// 确保仅在订单状态从任意状态变为“已完成”且支付方式为“货到付款”时执行
if ( $new_status === 'completed' && $order->get_payment_method() === 'dobirka' ) {
// 获取WooCommerce邮件器实例
$mailer = WC()->mailer();
// 定义邮件接收者、主题和消息体
$to = $order->get_billing_email();
$subject = sprintf( __( '您的订单 #%s 已完成 - 附赠礼品', 'your-text-domain' ), $order->get_order_number() );
$message_body = sprintf(
__( '亲爱的 %s,您的订单 #%s 已成功完成。感谢您的购买!我们随邮件附赠了一份小礼品,请查收。', 'your-text-domain' ),
$order->get_billing_first_name(),
$order->get_order_number()
);
// 包装邮件内容,包含邮件头部信息
// 第一个参数是邮件头,第二个参数是邮件体
$message = $mailer->wrap_message(
sprintf( __( '订单 %s 已完成', 'your-text-domain' ), $order->get_order_number() ),
$message_body
);
// 定义邮件头部,通常用于指定内容类型
$headers = 'Content-Type: text/html; charset=UTF-8';
// 定义附件路径
// WP_CONTENT_DIR 是 WordPress 内容目录的绝对路径,例如 /var/www/html/wp-content/
// 确保文件 'file.pdf' 实际存在于 wp-content 目录下
$attachments = array( WP_CONTENT_DIR . '/file.pdf' ); // 请替换为您的实际文件路径和文件名
// 发送邮件
// send 方法参数顺序: $to, $subject, $message, $headers, $attachments
$mailer->send( $to, $subject, $message, $headers, $attachments );
}
}
// 注册动作钩子
// 10 是优先级,4 是函数接受的参数数量 ($order_id, $old_status, $new_status, $order)
add_action( 'woocommerce_order_status_changed', 'action_woocommerce_order_status_changed_with_attachment', 10, 4 );action_woocommerce_order_status_changed_with_attachment 函数:
$mailer = WC()->mailer();:
邮件参数配置:
附件路径:
$mailer->send(...):
add_action( 'woocommerce_order_status_changed', 'action_woocommerce_order_status_changed_with_attachment', 10, 4 );:
文件路径的准确性:
$upload_dir = wp_upload_dir(); $attachment_path = $upload_dir['basedir'] . '/your-custom-folder/your-file.pdf'; $attachments = array( $attachment_path );
使用现代WooCommerce API:
国际化与可翻译性:
调试与测试:
通过遵循本文提供的代码示例和最佳实践,您可以有效地在WooCommerce自定义邮件中添加附件。核心在于理解邮件器的工作原理、正确构建附件的绝对路径,以及利用WooCommerce现代API进行开发。这不仅能满足业务需求,还能确保您的代码健壮、可维护且符合WordPress和WooCommerce的开发标准。
以上就是如何为WooCommerce自定义邮件添加附件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号