Using WordPress ‘get_comment_author()’ PHP function

The get_comment_author() WordPress PHP function retrieves the author of the current comment. If the comment has an empty comment_author field, then ‘Anonymous’ person is assumed.

Usage

$comment_author = get_comment_author($comment_id);

Example:

$comment_id = 15;
$comment_author = get_comment_author($comment_id);
echo $comment_author; // Outputs the author's name or 'Anonymous'

Parameters

  • $comment_id (int|WP_Comment) (Optional) – WP_Comment or the ID of the comment for which to retrieve the author. Default current comment.

More information

See WordPress Developer Resources: get_comment_author()

Examples

Get the author of a specific comment

This example retrieves the author name of a specific comment by passing the comment ID.

$comment_id = 10;
$author_name = get_comment_author($comment_id);
echo $author_name; // Outputs the author's name or 'Anonymous'

Display the author name of all comments on a post

This example retrieves and displays the author names for all comments on a post.

// Get comments for the current post
$comments = get_comments(array('post_id' => get_the_ID()));

// Loop through comments and display author name
foreach ($comments as $comment) {
    $author_name = get_comment_author($comment->comment_ID);
    echo $author_name . '<br>';
}

Use the function inside the comment loop

This example demonstrates how to use the get_comment_author() function inside the comment loop.

// Start the comment loop
if (have_comments()) :
    while (have_comments()) : the_comment();
        $author_name = get_comment_author();
        echo $author_name . '<br>';
    endwhile;
endif;

Display comment author name with a fallback

This example retrieves the author name of a specific comment and displays a fallback text if the author name is ‘Anonymous’.

$comment_id = 25;
$author_name = get_comment_author($comment_id);
if ($author_name == 'Anonymous') {
    $author_name = 'Guest User';
}
echo $author_name;

Get the author of the current comment in a custom comment callback

This example demonstrates how to use the get_comment_author() function inside a custom comment callback function.

function custom_comment_callback($comment, $args, $depth) {
    $author_name = get_comment_author($comment);
    echo $author_name . '<br>';
}

wp_list_comments(array('callback' => 'custom_comment_callback'));