Using WordPress ‘comment_author’ PHP filter

The comment_author WordPress PHP filter allows you to modify the comment author’s name before it’s displayed.

Usage

add_filter('comment_author', 'your_custom_function', 10, 2);

function your_custom_function($author, $comment_id) {
  // your custom code here
  return $author;
}

Parameters

  • $author (string) – The comment author’s username.
  • $comment_id (string) – The comment ID as a numeric string.

More information

See WordPress Developer Resources: comment_author

Examples

Change all comment author names to “Anonymous”

Make all the comment authors’ names appear as “Anonymous”:

add_filter('comment_author', 'change_author_to_anonymous', 10, 2);

function change_author_to_anonymous($author, $comment_id) {
  return "Anonymous";
}

Add “Guest” prefix to non-registered users

Add the prefix “Guest” to comment authors who are not registered users:

add_filter('comment_author', 'add_guest_prefix', 10, 2);

function add_guest_prefix($author, $comment_id) {
  $comment = get_comment($comment_id);
  if ($comment->user_id == 0) {
    return "Guest " . $author;
  }
  return $author;
}

Uppercase comment author names

Make all the comment author names uppercase:

add_filter('comment_author', 'uppercase_author_name', 10, 2);

function uppercase_author_name($author, $comment_id) {
  return strtoupper($author);
}

Replace specific author names with a custom name

Replace specific author names with a custom name:

add_filter('comment_author', 'replace_specific_author_name', 10, 2);

function replace_specific_author_name($author, $comment_id) {
  $custom_name = "Custom Name";
  $names_to_replace = array('John Doe', 'Jane Doe');

  if (in_array($author, $names_to_replace)) {
    return $custom_name;
  }
  return $author;
}

Add a custom CSS class to the comment author name

Add a custom CSS class to style the comment author name:

add_filter('comment_author', 'add_custom_css_class', 10, 2);

function add_custom_css_class($author, $comment_id) {
  return '<span class="custom-author-class">' . $author . '</span>';
}