The get_comment_author_IP WordPress PHP filter allows you to modify the comment author’s IP address before it’s returned.
On this pageJump to a section
Usage
add_filter( 'get_comment_author_IP', 'your_custom_function', 10, 3 );
function your_custom_function( $comment_author_ip, $comment_id, $comment ) {
// your custom code here
return $comment_author_ip;
}
Parameters
$comment_author_ip (string)– The comment author’s IP address or an empty string if it’s not available.$comment_id (string)– The comment ID as a numeric string.$comment (WP_Comment)– The comment object.
More information
See WordPress Developer Resources: get_comment_author_IP
Examples
Anonymize IP Addresses
To anonymize comment author IP addresses by removing the last octet:
add_filter( 'get_comment_author_IP', 'anonymize_comment_author_IP', 10, 3 );
function anonymize_comment_author_IP( $comment_author_ip, $comment_id, $comment ) {
$ip_parts = explode( '.', $comment_author_ip );
$ip_parts[3] = 'xxx';
$anonymized_ip = implode( '.', $ip_parts );
return $anonymized_ip;
}
Display “Unknown” for Empty IP Addresses
To display “Unknown” for comment authors with empty IP addresses:
add_filter( 'get_comment_author_IP', 'display_unknown_for_empty_ips', 10, 3 );
function display_unknown_for_empty_ips( $comment_author_ip, $comment_id, $comment ) {
if ( empty( $comment_author_ip ) ) {
return __( 'Unknown', 'text-domain' );
}
return $comment_author_ip;
}
Append Country Code to IP Address
To append the comment author’s country code to their IP address using an external API:
add_filter( 'get_comment_author_IP', 'append_country_code_to_ip', 10, 3 );
function append_country_code_to_ip( $comment_author_ip, $comment_id, $comment ) {
$country_code = get_country_code_from_ip( $comment_author_ip );
return $comment_author_ip . ' (' . $country_code . ')';
}
Replace Local IP Addresses with “Local”
To replace local IP addresses (127.0.0.1) with the text “Local”:
add_filter( 'get_comment_author_IP', 'replace_local_ip', 10, 3 );
function replace_local_ip( $comment_author_ip, $comment_id, $comment ) {
if ( '127.0.0.1' === $comment_author_ip ) {
return __( 'Local', 'text-domain' );
}
return $comment_author_ip;
}
Hide IP Addresses for Specific User Roles
To hide IP addresses for specific user roles, such as “administrator” and “editor”:
add_filter( 'get_comment_author_IP', 'hide_ip_for_specific_roles', 10, 3 );
function hide_ip_for_specific_roles( $comment_author_ip, $comment_id, $comment ) {
$user = get_user_by( 'email', $comment->comment_author_email );
if ( $user && ( user_can( $user, 'administrator' ) || user_can( $user, 'editor' ) ) ) {
return __( 'Hidden', 'text-domain' );
}
return $comment_author_ip;
}