Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.