Using WordPress ‘get_comment_author_IP()’ PHP function

The get_comment_author_IP() WordPress PHP function retrieves the IP address of the author of the current comment.

Usage

$author_IP = get_comment_author_IP($comment_id);

Parameters

  • $comment_id (int|WP_Comment, Optional): WP_Comment or the ID of the comment for which to get the author’s IP address. Default is the current comment.

More information

See WordPress Developer Resources: get_comment_author_IP()

Examples

Get IP address of a specific comment

$comment_id = 42; // The ID of the comment you want to get the IP address for
$author_IP = get_comment_author_IP($comment_id);
echo "The IP address of the comment author is: " . $author_IP;

Display IP address for each comment on a post

$comments = get_comments(array('post_id' => get_the_ID()));
foreach ($comments as $comment) {
    $author_IP = get_comment_author_IP($comment);
    echo "IP address for comment " . $comment->comment_ID . ": " . $author_IP . "<br>";
}

Filter comments by IP address

$ip_to_filter = '192.168.1.1';
$comments = get_comments();
foreach ($comments as $comment) {
    $author_IP = get_comment_author_IP($comment);
    if ($author_IP == $ip_to_filter) {
        echo "Comment ID " . $comment->comment_ID . " has IP address: " . $author_IP . "<br>";
    }
}

Log comment IP addresses for moderation purposes

function log_comment_IP_addresses($comment_id) {
    $comment = get_comment($comment_id);
    $author_IP = get_comment_author_IP($comment);
    error_log("Comment ID " . $comment_id . " has IP address: " . $author_IP);
}
add_action('comment_post', 'log_comment_IP_addresses', 10, 1);

Display a message to the comment author based on their IP address

$comment = get_comment(123); // Replace with a valid comment ID
$author_IP = get_comment_author_IP($comment);
$special_ip = '10.0.0.1';

if ($author_IP == $special_ip) {
    echo "Hello, special user from IP " . $author_IP . "!";
} else {
    echo "Hello, user from IP " . $author_IP . "!";
}