Using WordPress ‘comment_author()’ PHP function

The comment_author() WordPress PHP function is used to display the author of the current comment.

Usage

Let’s say we want to display the author name of a comment in a <div> element. We can use the comment_author() function like this:

<div>Comment by: 
comment_author();
</div>

Parameters

  • $comment_id (int|WP_Comment): This is an optional parameter. You can pass either a WP_Comment object or the ID of the comment for which you want to print the author. If this parameter is not provided, the function will print the author of the current comment.

More information

See WordPress Developer Resources: comment_author()

Examples

Displaying Comment Author Without Parameter

This is the most basic usage of the function. It will print the author of the current comment.

<div>
  Comment by: 
  comment_author(); // displays the author of the current comment
</div>

Displaying Comment Author With Comment ID

This example demonstrates how to print the author of a specific comment by passing the comment ID as a parameter.

$comment_id = 10; // let's say we have a comment with ID 10
comment_author($comment_id); // displays the author of the comment with ID 10

Displaying Comment Author Within a Loop

In this example, we are looping through an array of comment IDs and printing the author of each comment.

$comment_ids = array(1, 2, 3, 4, 5); // an array of comment IDs

foreach ($comment_ids as $comment_id) {
  comment_author($comment_id); // displays the author of each comment
}

Displaying Comment Author With WP_Comment Object

You can also pass a WP_Comment object to the function. This example shows how to do it.

$comment = get_comment(1); // get the WP_Comment object for the comment with ID 1
comment_author($comment); // displays the author of the comment

Displaying Comment Author Within a Custom Function

In this example, we are creating a custom function that accepts a comment ID as a parameter and uses the comment_author() function to print the author.

function display_comment_author($comment_id) {
  comment_author($comment_id); // displays the author of the comment
}

display_comment_author(1); // call the custom function with a comment ID