我在这篇博客留言提醒自己增加这个需求:https://heybran.tech/node-js-testing-notes/#comment-54,在此记录一下实现的代码。查看了WordPress关于留言表单的源码:https://github.com/WordPress/wordpress-develop/blob/6.6.2/src/wp-includes/comment-template.php#L2784,我可以在comment_form_field_comment这个filter上面添加一个回调函数。
add_filter('comment_form_field_comment', function ($comment_field) {
if (!current_user_can('manage_options')) {
return $comment_field;
}
$notify_users_field = sprintf(
'<p class="comment-form-notify-users">%s %s</p>',
sprintf(
'<label for="notify-users">%s</label>',
__('通知用户')
),
'<input id="notify-users" name="notify-users" type="email" size="30" maxlength="100" placeholder="邮件地址用英文逗号隔开" />'
);
return $comment_field . $notify_users_field;
});
代码部署后前端效果 (不过这个输入框仅管理员可见):
增加了一个邮件输入框来添加想要通知的邮箱,单独这个还不行,还需要监听这个comment_post
事件。
add_action('comment_post', function ($comment_ID) {
$comment = get_comment($comment_ID);
// Only proceed if the current user is an admin and if the notify-users field is set
if (current_user_can('manage_options') && !empty($_POST['notify-users'])) {
// Sanitize and split the emails by commas
$emails = explode(',', sanitize_text_field($_POST['notify-users']));
// Get the comment and post information.
$post = get_post($comment->comment_post_ID);
// Loop through each email, validate, and send the email.
foreach ($emails as $email) {
$email = trim($email); // Remove any surrounding whitespace.
if (is_email($email)) { // Check if it's a valid email address.
wp_mail(
$email,
sprintf(__('Brandon在他的文章留言中@到了您 - %s'), $post->post_title),
sprintf(
__("Brandon在文章中添加了以下留言并提及到您:\n\n%s\n\n点击访问文章: %s"),
get_comment_text($comment_ID),
get_permalink($post)
)
);
}
}
}
});