Delete Spam Comments Older Than 30 Days
Permanently removes comments marked as spam once they are older than 30 days, so spammers' names, emails and IP addresses do not pile up in your database.
Opens WPIDE on
Code
// Days to keep spam before it is deleted.
$wpide_spam_days = 30;
add_action( 'init', function () {
if ( ! wp_next_scheduled( 'wpide_purge_old_spam' ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'wpide_purge_old_spam' );
}
} );
add_action( 'wpide_purge_old_spam', function () use ( $wpide_spam_days ) {
global $wpdb;
$ids = $wpdb->get_col( $wpdb->prepare(
"SELECT comment_ID FROM {$wpdb->comments} WHERE comment_approved = 'spam' AND comment_date_gmt < %s LIMIT 200",
gmdate( 'Y-m-d H:i:s', time() - $wpide_spam_days * DAY_IN_SECONDS )
) );
foreach ( $ids as $id ) {
wp_delete_comment( (int) $id, true );
}
} );
Notes
Runs daily in batches of 200; check the Spam folder now and then if you rely on rescuing false positives.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.