我有一个WordPress网站,用户可以从前端发布,状态为草稿。
现在当我从管理面板发布帖子时,通知电子邮件发送了不止一次。我需要发一次邮件。
我的代码下面:
if (is_admin()) {
function notifyauthor($post_id) {
$post = get_post($post_id);
$author = get_userdata($post->post_author);
$subject = "Post publish notification";
$headers = 'From: '.get_bloginfo( 'name' ).' <my_email@gmail.com>' . "rn";
$message = "
Hi ".$author->display_name.",
Your post, "".$post->post_title."" has just been published.
View post: ".get_permalink( $post_id )."
Thank You, Admin"
;
wp_mail($author->user_email, $subject, $message, $headers);
}
add_action('publish_post', 'notifyauthor');
}
我尝试了current_user_can('administrator')
而不是is_admin()
,但我得到了相同的结果。
许多钩子实际上会运行不止一次。简单的解决方案是在第一次迭代之后通过post_meta添加一个计数器,然后检查它是否存在。
function notifyauthor($post_id) {
if (is_admin() && !(metadata_exists('post', $post_id, 'sent_notification_email'))) {
$post = get_post($post_id);
$author = get_userdata($post->post_author);
$subject = "Post publish notification";
$headers = 'From: '.get_bloginfo( 'name' ).' <my_email@gmail.com>' . "rn";
$message = "
Hi ".$author->display_name.",
Your post, "".$post->post_title."" has just been published.
View post: ".get_permalink( $post_id )."
Thank You, Admin";
wp_mail($author->user_email, $subject, $message, $headers);
// Set a meta key as a counter
update_post_meta($post_id, 'sent_notification_email', '1');
}
}
add_action('publish_post', 'notifyauthor');