Open1

WordPress いじるときのあれこれ

naonao

コメントの通知先を変更する

TL, DR

次のようなコードを書いて、無事に管理者メールアドレスから変更できた。めでたし。

function custom_comment_recipients( $recipients ) {
    $admin_email = get_option( 'admin_email' );

    // 管理者アドレスを通知先から除外
    $recipients = array_diff( $recipients, array( $admin_email ) );

    $recipients[] = /** <変更したいメールアドレス> **/;

    return $recipients;
}
add_filter( 'comment_moderation_recipients', 'custom_comment_recipients' );

投稿にコメントされたときの通知先メールアドレスは管理者のものになるが、この通知先を変更したいことがある。

調べてみると、comment_post フックを使ってフック関数内で wp_mail を呼び出して通知させるような情報があった。ChatGPT(4o-mini)も comment_post を使えという。

https://developer.wordpress.org/reference/hooks/comment_post/

ただ、上記のやり方だと設定画面の通知設定をオフにしても通知されてしまう(未検証)。


ディスカッション設定画面。チェックを外したら通知はしたくない

通知先のメールアドレスだけ変更できないのか。仕方なくコードを読んだ。

上記設定で管理者宛のメール通知処理は wp_notify_moderator 関数でやってるぽい。

それらしい hooks を発見

https://github.com/WordPress/WordPress/blob/708282ecafecdb0e226b587fc38f7c3956ac8409/wp-includes/pluggable.php#L1934-L1942

comment_moderation_recipients フックで通知先のメールアドレス(リスト)を更新できるらしい。

https://developer.wordpress.org/reference/hooks/comment_moderation_recipients/