Php 在Wordpress中首次发布帖子时发送通知邮件
我试图在Wordpress中创建一个推荐表单和列表页面,但我在向推荐作者发送电子邮件,通知他他的帖子已经发布时遇到了问题 表单验证和处理后,它会自动使用Php 在Wordpress中首次发布帖子时发送通知邮件,php,wordpress,email,advanced-custom-fields,Php,Wordpress,Email,Advanced Custom Fields,我试图在Wordpress中创建一个推荐表单和列表页面,但我在向推荐作者发送电子邮件,通知他他的帖子已经发布时遇到了问题 表单验证和处理后,它会自动使用wp\u insert\u post()创建一个挂起的帖子,表单详细信息存储在高级自定义字段插件生成的文本输入中。当我点击发布按钮时,它会向作者发送一封通知电子邮件。以下是我编写的函数: function publish_post_notification($post_id){ $author = get_field('author_ema
wp\u insert\u 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\u post
钩子,但它在最初通过wp\u insert\u post()
创建帖子时也会触发,并且由于某种原因转换\u post\u状态
,挂起到发布
和更新后的状态
对我也不起作用
有什么建议吗
提前感谢我发现了我的代码的错误:来自高级自定义字段的
get_field()
函数在第一次发布后没有返回author字段值,因此if(isset($author))
条件返回false
我更改了$author=get\u字段('author\u email',$post\u id)代码>到
$author=get\u post\u meta($post\u id,'author\u email',true)
现在它可以工作了使用save post钩子并检查函数中的post状态。您可以设置post meta以防止进一步的电子邮件。您能给我一个例子吗?我如何检查帖子是否正在创建,这样钩子就不会触发?请先自己尝试,您可以使用get\u post
来拉帖子,然后使用update\u post\u meta()
来保存自定义数据。谢谢您的建议。我最终发现了问题所在,并在下面发布了答案。你是说“作者电子邮件”而不是“电子邮件客户端”,对吗?你是对的,我复制粘贴代码时可能忘了更改名称。我试图在发布之前翻译我的变量名。现在改了。