Automatically deleting WordPress comments using a theme
Let's say you want to automatically delete specific sorts of comments from your WordPress blog. For example, immediately trashing any comment that has a specific phrase "Elephant Juice" in it.
You can do this by going to Settings -> Discussion → Disallowed Comment Keys. Or you can add something to your theme's functions.php
file.
Here's the code snippet:
PHP
add_action( 'comment_post', 'check_comment_content', 10, 2 );
function check_comment_content( $comment_id, $comment_approved ) {
$comment = get_comment( $comment_id );
// Check if the comment body contains the text "Elephant Juice"
if (stripos( $comment->comment_content, 'Elephant Juice') !== false ) {
// Set the comment status to 'trash'
wp_delete_comment( $comment_id );
}
}
The comment_post
hook is invoked immediately after a comment is received.
The comment is then retrieved by the function, checked for its content, and then deleted with wp_delete_comment
. If you're absolutely sure you don't want it in the trash (where it will stay for 30 days) you can call wp_delete_comment( $comment_id, true );
and it will be instantly obliterated.
But it isn't just the comment's text that you can filter on. The comment object will look something like this (depending on what weird plugins you have installed):
PHP
[comment_ID] => 123456
[comment_post_ID] => 789
[comment_author] => Fred Flintstone
[comment_author_email] => fred@example.com
[comment_author_url] => https://example.com/@f_flintstone
[comment_author_IP] => 203.0.113.123
[comment_date] => 2023-08-29 07:13:57
[comment_date_gmt] => 2023-08-29 07:13:57
[comment_content] => Elephant Juice
[comment_karma] => 0
[comment_approved] => 0
[comment_agent] => Bridgy (https://brid.gy/about)
[comment_type] => like
[comment_parent] => 0
[user_id] => 0
...
So you can block comment by User Agent, IP address, and anything else you like. I use it to filter out specific WebMentions.