Permanently delete comments that have been marked as spam for more than 15 days, in daily batches.
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 );
}
} );
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.
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.
15 days ago if you want a longer grace period.Run the task with WP Crontrol or wp cron event run nahnu_delete_old_spam, then check Comments → Spam: only recent spam should remain.