automatically delete spam comments in wordpress

automatically delete spam comments in wordpress

WordPress Spam comments is big issue. I am getting daily 5k spam comments daily. we automated task of  deleting spam comments automatically. Daily going to comments dashboard and deleting spam comments is really boring task. WordPress Akismat wordpress plugin does good job of finding spam comments.

automatically delete spam comments in wordpress
automatically delete spam comments in wordpress

 

How to automatically delete spam comments in wordpress?

I am using Akismat wordpress plugin for my all wordpress blogs. It does good job of finding spam comments. Due to spam comments. comment-meta table becoming big and causing mysql resource issues. So cleaning comments table became necessary. so we used following hook in wordpress theme code.


function auto_delete_spam_comments() {
$in_progress = (bool) get_site_option( 'spamcomment_delete_in_progress' );
if ( ! $in_progress ) {
global $wpdb;
update_site_option( 'spamcomment_delete_in_progress', '1' );
// 4980
$next = (int) get_site_option( 'spamcomments_delete_next_blog' );
if ( empty( $next ) ) {
$next = 1;
}

if ( $next > 3000 ) {
return;
}
switch_to_blog( $next );

$spams = $wpdb->get_col( "SELECT comment_id FROM {$wpdb->comments} WHERE comment_approved = 'spam' LIMIT 10" );
if ( empty( $spams ) ) {
$next++;
update_site_option( 'spamcomments_delete_next_blog', $next );
} else {
foreach ( $spams as $spam ) {
wp_delete_comment( $spam, true );
$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->commentmeta} WHERE comment_id = %d", $spam ) );
}
}
// reclaim disk space
$wpdb->query( "OPTIMIZE TABLE {$wpdb->comments}" );
$wpdb->query( "OPTIMIZE TABLE {$wpdb->commentmeta}" );
restore_current_blog();
delete_site_option( 'spamcomment_delete_in_progress' );
}
}
register_shutdown_function( 'auto_delete_spam_comments' );

Notes:
The number of blogs is hardcoded (3000)
Add above code in functions.php file.

If you want WordPress to automatically empty my spam comments after 1 day. Just add this to wp-config.php. Following code will automatically Empty Your WordPress Trash

/**
 * Delete Spam Comments.
 */
define( 'EMPTY_TRASH_DAYS', 1 );

To disable trash set the number of days to zero. Note that WordPress will not ask for confirmation when someone clicks on “Delete Permanently”.

define( 'EMPTY_TRASH_DAYS', 0 ); // Zero days

If you want more information Automatically empty wordpress Trash comments and posts and How to make empty wordpress trash automatically

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

Leave a Reply

Your email address will not be published.