Performance PHP Intermediate

Delete Old Spam Comments Automatically

Permanently delete comments that have been marked as spam for more than 15 days, in daily batches.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 18 lines
add_action( 'init', function (): void {
	if ( ! wp_next_scheduled( 'nahnu_delete_old_spam' ) ) {
		wp_schedule_event( time(), 'daily', 'nahnu_delete_old_spam' );
	}
} );

add_action( 'nahnu_delete_old_spam', function (): void {
	$spam = get_comments( [
		'status'     => 'spam',
		'number'     => 500,
		'fields'     => 'ids',
		'date_query' => [ [ 'column' => 'comment_date_gmt', 'before' => '15 days ago' ] ],
	] );

	foreach ( $spam as $comment_id ) {
		wp_delete_comment( (int) $comment_id, true );
	}
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Spam comments stay in the database until someone empties the Spam folder, and on popular sites that can be hundreds of thousands of rows. This snippet deletes spam older than 15 days every day.

How it works

A daily scheduled task fetches up to 500 spam comment IDs older than 15 days and deletes each permanently with wp_delete_comment( $id, true ), which also removes their comment meta. Batches keep each run quick.

The 15-day grace period gives you time to rescue anything wrongly marked as spam.

Things to watch

  • Akismet already deletes spam older than 15 days on sites where it’s active. You don’t need both.
  • Change 15 days ago if you want a longer grace period.

How to test it

Run the task with WP Crontrol or wp cron event run nahnu_delete_old_spam, then check Comments → Spam: only recent spam should remain.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only