# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Privacy & Cookies](https://wpide.com/library/category/privacy/)
- Tags: comments, spam, retention
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/privacy-purge-old-spam-comments/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Delete Spam Comments Older Than 30 Days" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
