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).

3 s
3

You are missing a “NOT” logical operator (!) in your if statement.
You want to say “if comment author IS NOT empty”. As of now, the function is reading that the author is not empty and defaulting to your else statement that tells it to output the author’s full name. Use the second block of code but make the following change.

Change the following:

if ( empty($comment->comment_author) ) {

to:

if ( !empty($comment->comment_author) ) {

Otherwise it looks ok to me.

Leave a Reply

Your email address will not be published. Required fields are marked *