我有一個 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' ).' <[email protected]>' . "\r\n";
$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(),但得到了同樣的結果。
uj5u.com熱心網友回復:
許多鉤子實際上會運行不止一次。簡單的解決方案是在第一次迭代后通過 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' ).' <[email protected]>' . "\r\n";
$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');
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/324556.html
標籤:WordPress的
