Include Custom Comment Fields in Privacy Exports and Erasures
Adds extra comment fields stored as comment meta (such as a phone number or rating) to personal data exports, and removes them during erasure requests.
Opens WPIDE on
Code
// Comment meta key => label in the export.
$wpide_comment_meta_fields = array(
'phone' => 'Phone number',
'rating' => 'Rating',
);
$wpide_comment_ids_for = function ( $email, $page ) {
return get_comments( array(
'author_email' => $email,
'number' => 100,
'paged' => max( 1, (int) $page ),
'fields' => 'ids',
'status' => 'all',
'orderby' => 'comment_ID',
'order' => 'ASC',
) );
};
add_filter( 'wp_privacy_personal_data_exporters', function ( $exporters ) use ( $wpide_comment_meta_fields, $wpide_comment_ids_for ) {
$exporters['wpide-comment-meta'] = array(
'exporter_friendly_name' => 'Extra comment fields',
'callback' => function ( $email, $page = 1 ) use ( $wpide_comment_meta_fields, $wpide_comment_ids_for ) {
$ids = $wpide_comment_ids_for( $email, $page );
$items = array();
foreach ( $ids as $id ) {
$data = array();
foreach ( $wpide_comment_meta_fields as $key => $label ) {
$value = get_comment_meta( $id, $key, true );
if ( '' !== $value ) {
$data[] = array( 'name' => $label, 'value' => is_scalar( $value ) ? (string) $value : wp_json_encode( $value ) );
}
}
if ( $data ) {
$items[] = array( 'group_id' => 'comments', 'group_label' => 'Comments', 'item_id' => 'comment-' . $id, 'data' => $data );
}
}
return array( 'data' => $items, 'done' => count( $ids ) < 100 );
},
);
return $exporters;
} );
add_filter( 'wp_privacy_personal_data_erasers', function ( $erasers ) use ( $wpide_comment_meta_fields, $wpide_comment_ids_for ) {
$erasers['wpide-comment-meta'] = array(
'eraser_friendly_name' => 'Extra comment fields',
'callback' => function ( $email, $page = 1 ) use ( $wpide_comment_meta_fields, $wpide_comment_ids_for ) {
$ids = $wpide_comment_ids_for( $email, $page );
$removed = false;
foreach ( $ids as $id ) {
foreach ( array_keys( $wpide_comment_meta_fields ) as $key ) {
$removed = delete_comment_meta( $id, $key ) || $removed;
}
}
return array( 'items_removed' => $removed, 'items_retained' => false, 'messages' => array(), 'done' => count( $ids ) < 100 );
},
);
return $erasers;
} );
Notes
List the comment meta keys your comment form or plugins store; each request handles up to 100 comments per page.
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.