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.
Opens WPIDE on
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
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.