Help with functions code to change comment_author to first_name

Help with functions code to change comment_author to first_name

I have this line of code below that displays the comment_author,

But the comment_author is the Username, so for security I would like to display the users first_name,

<h6 class="message-author"><a href="<?php echo get_author_posts_url($comment->user_id); ?>"><?php comment_author(); ?></a></h6>

I have tried changing the comment_author in the code above, yet without success,

So I was thinking it could be done with an add_filter in the functions.php

add_filter(
if ($comment->comment_author) {
change to first_name

Is this the correct/best way of accomplishing what I want? all help appreciated :slight_smile:

having a look at the specific function in

https://core.trac.wordpress.org/browser/tags/4.5.2/src/wp-includes/comment-template.php#L0

comment_author() is utilizing the return value of get_comment_author() which invokes $author = $user->display_name; so you can change this to your appropriate database column, or better extend the function signature with an optional parameter.

1 Like

Hello chorn, thank you for your reply, but you are speaking a language I do not understand … coding :slight_smile:

I was hoping for someone to tell me what code to use in the functions.php or if the

```<?php comment_author(); ?>`

could be changed ? so as to display the first_name.

I think you’re looking for the_author_meta

1 Like

Hello Mittineague, thank you for your quick reply and information, I will try your code and reply back once tested :slight_smile:

Thank you to all helping contributors, I have found a solution by placing this code into the functions.php

/**
 * Changes name displayed in messages/comments from Username to First Name & Last 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,30).' '; // change to first name last name
        } else {
            $author = __('Anonymous');
        }
    } else {
        $author = $comment->comment_author;
    }

    return $author;
}

One Question? In the line below, what does the 10, 1 refer to ?

add_filter('get_comment_author', 'my_comment_author', 10, 1);

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.