I am trying to change the comment author name (or more specifically, the review author in WooCommerce) to be First name Last Initial (e.g., "John D." for "John Doe").
I got most of the way there with the following code in functions.php, but for some reason (perhaps because of how the comment/review was submitted) it tends to blank out the name and replace it with a period (".") in some (not all) of the reviews.
add_filter('get_comment_author', 'my_comment_author', 10, 1);
function my_comment_author( $author = '' ) {
// Get the comment ID from WP_Query
$comment = get_comment( $comment_ID );
if ( empty($comment->comment_author) ) {
if (!empty($comment->user_id)){
$user=get_userdata($comment->user_id);
$author=$user->first_name.' '.substr($user->last_name,0,1).'.'; // this is the actual line you want to change
} else {
$author = __('Anonymous');
}
} else {
$user=get_userdata($comment->user_id);
$author=$user->first_name.' '.substr($user->last_name,0,1).'.'; // this is the actual line you want to change
}
return $author;
}
If I tweak the code like this as a fallback, however, it always displays the full name:
add_filter('get_comment_author', 'my_comment_author', 10, 1);
function my_comment_author( $author = '' ) {
// Get the comment ID from WP_Query
$comment = get_comment( $comment_ID );
if ( empty($comment->comment_author) ) {
if (!empty($comment->user_id)){
$user=get_userdata($comment->user_id);
$author=$user->first_name.' '.substr($user->last_name,0,1).'.'; // this is the actual line you want to change
} else {
$author = __('Anonymous');
}
} else {
$author = $comment->comment_author;
}
return $author;
}
I would prefer to leave the actual names in the database intact, and just filter the output on the public-facing side of the site for comments (we might need their full name to display elsewhere, but can't really test it until the comment authors are displaying correctly).