Using WordPress ‘comment_author_IP()’ PHP function

The comment_author_IP() WordPress PHP function displays the IP address of the author of the current comment.

Usage

You can use the comment_author_IP() function in your WordPress theme files, usually within the comments loop. For instance, if you want to display the comment author’s IP address in your comments section:

// Inside your WordPress comments loop
echo 'IP: ' . comment_author_IP();

This will output something like: IP: 192.168.1.1, where 192.168.1.1 is the IP address of the comment author.

Parameters

  • $comment_id (int|WP_Comment) – Optional. This is either a WP_Comment object or the ID of the comment for which you want to print the author’s IP address. By default, it refers to the current comment.

More information

See WordPress Developer Resources: comment_author_IP()

Note that as of WordPress 4.4.0, comment IPs are no longer stored for comments submitted by a logged-in user with the capability to manage comments.

Examples

Displaying IP in the comments loop

This function is typically used in the comments loop. Here, we’re directly echoing the IP of the comment author.

// Inside your comments loop
echo 'Comment Author IP: ' . comment_author_IP();

Storing IP in a variable

You can also store the IP in a variable for later use.

// Inside your comments loop
$author_ip = comment_author_IP();
// Use $author_ip somewhere later in your code

Checking for a specific IP

Here, we’re checking if the comment author’s IP matches a specific IP.

// Inside your comments loop
if ( comment_author_IP() == '192.168.1.1' ) {
    echo 'Hello, Admin!';
}

Display IP for a specific comment

You can also get the IP of a specific comment by passing the comment ID or WP_Comment object as a parameter.

// Assume $comment is a WP_Comment object for a specific comment
echo 'IP: ' . comment_author_IP( $comment );

Display only if IP exists

In some cases, there may not be an IP associated with a comment. Here, we’re only showing the IP if it exists.

// Inside your comments loop
$author_ip = comment_author_IP();
if ( ! empty( $author_ip ) ) {
    echo 'IP: ' . $author_ip;
}