【问题标题】:Send notification mail the first time a post is published in Wordpress首次在 Wordpress 中发布帖子时发送通知邮件
【发布时间】: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_statuspending_to_publishpost_updated 不起作用我也是。

有什么建议吗?

提前致谢

【问题讨论】:

  • 使用保存帖子钩子并检查功能内的帖子状态。您可以设置帖子元以防止进一步的电子邮件。
  • 你能给我举个例子吗?我将如何检查是否正在创建帖子以便钩子不会触发?
  • 自己试试,可以用get_post拉帖,再用update_post_meta()保存自定义数据。
  • 感谢您的建议。我最终发现了问题所在,并在下面发布了答案。

标签: php wordpress email advanced-custom-fields


【解决方案1】:

我发现我的代码有什么问题:高级自定义字段中的 get_field() 函数在第一次发布时没有返回作者字段值,因此 if(isset($author)) 条件返回 false。

我已将$author = get_field('author_email', $post_id); 更改为 $author = get_post_meta($post_id, 'author_email', true); 现在可以使用了

【讨论】:

  • 你的意思是“author_email”而不是“email_pacient”,对吧?
  • 你说得对,可能是我复制粘贴代码时忘记更改名称了。我试图在发布之前翻译我的变量名。现在改了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多