Halloween Sale 15% off Ends in See the plans
PHP

Anonymize Comment IP Addresses After 60 Days

Once a day, shortens the stored IP address of approved comments older than 60 days, so you keep recent IPs for spam handling without holding personal data forever.

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

Code

// Keep full IP addresses for this many days.
$wpide_ip_retention_days = 60;

add_action( 'init', function () {
    if ( ! wp_next_scheduled( 'wpide_anonymize_comment_ips' ) ) {
        wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'wpide_anonymize_comment_ips' );
    }
} );

add_action( 'wpide_anonymize_comment_ips', function () use ( $wpide_ip_retention_days ) {
    global $wpdb;

    $cutoff = gmdate( 'Y-m-d H:i:s', time() - $wpide_ip_retention_days * DAY_IN_SECONDS );
    $rows   = $wpdb->get_results( $wpdb->prepare(
        "SELECT comment_ID, comment_author_IP FROM {$wpdb->comments}
         WHERE comment_date_gmt < %s AND comment_approved = '1' AND comment_author_IP <> ''
         AND comment_author_IP NOT LIKE %s AND comment_author_IP NOT LIKE %s LIMIT 500",
        $cutoff,
        '%.0',
        '%::'
    ) );

    foreach ( $rows as $row ) {
        $wpdb->update( $wpdb->comments, array( 'comment_author_IP' => wp_privacy_anonymize_ip( $row->comment_author_IP ) ), array( 'comment_ID' => (int) $row->comment_ID ) );
        clean_comment_cache( (int) $row->comment_ID );
    }
} );

Notes

Change $wpide_ip_retention_days to your retention period; already-shortened addresses are skipped.

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.