【发布时间】:2015-09-22 22:59:12
【问题描述】:
我正在尝试在 Wordpress 中创建推荐表格和列表页面,但我无法向推荐作者发送电子邮件,通知他他的帖子已发布。
验证和处理表单后,它会自动创建一个带有wp_insert_post() 的待处理帖子,并且表单详细信息存储在高级自定义字段插件生成的文本输入中。当我单击发布按钮时,它应该向作者发送一封通知电子邮件。这是我写的函数:
function publish_post_notification($post_id){
$author = get_field('author_email', $post_id); // get author email from custom fields
if(isset($author)){
require_once('testimoniale/mail-config.php'); // PHPMailer config
$mail->addAddress($author); // Add a recipient
$mail->Subject = 'Your testimonial has been published !';
ob_start();
include('testimoniale/mail_template/notification-template.php');
$mail->Body = ob_get_contents();
$mail->AltBody = 'Your testimonial has been published !'; // Alternative text for non-html mail clients
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
ob_end_clean();
}
add_action('publish_post','publish_post_notification',10,1);
问题是当我第一次发布帖子时,它不会发送电子邮件,但如果我之后将帖子状态更改为待处理并再次发布或更新帖子,它会发送电子邮件.
我尝试过使用save_post 钩子,但是当最初通过wp_insert_post() 创建帖子时它也会触发,并且由于某种原因transition_post_status、pending_to_publish 和post_updated 不起作用我也是。
有什么建议吗?
提前致谢
【问题讨论】:
-
使用保存帖子钩子并检查功能内的帖子状态。您可以设置帖子元以防止进一步的电子邮件。
-
你能给我举个例子吗?我将如何检查是否正在创建帖子以便钩子不会触发?
-
自己试试,可以用
get_post拉帖,再用update_post_meta()保存自定义数据。 -
感谢您的建议。我最终发现了问题所在,并在下面发布了答案。
标签: php wordpress email advanced-custom-fields