How to display the “custom nickname” on Wordpress Comments?

微笑、不失礼 提交于 2021-02-11 12:44:52

问题


When I post a comment, it prints always the non-editable nickname set on the Users CMS area. I'd like to print the custom nickname (the one that can be chosed by dropdown list).

I actually use comment_author_link(); and seems it is not enough. How can I should use?


回答1:


WordPress uses the following code to retrieve the author of the current comment:

/**
 * Retrieve the author of the current comment.
 *
 * If the comment has an empty comment_author field, then 'Anonymous' person is
 * assumed.
 *
 * @since 1.5.0
 * @uses apply_filters() Calls 'get_comment_author' hook on the comment author
 *
 * @param int $comment_ID The ID of the comment for which to retrieve the author. Optional.
 * @return string The comment author
 */
function get_comment_author( $comment_ID = 0 ) {
    $comment = get_comment( $comment_ID );
    if ( empty($comment->comment_author) ) {
        if (!empty($comment->user_id)){
            $user=get_userdata($comment->user_id);
            $author=$user->user_login;
        } else {
            $author = __('Anonymous');
        }
    } else {
        $author = $comment->comment_author;
    }
    return apply_filters('get_comment_author', $author);
}

/**
 * Displays the author of the current comment.
 *
 * @since 0.71
 * @uses apply_filters() Calls 'comment_author' on comment author before displaying
 *
 * @param int $comment_ID The ID of the comment for which to print the author. Optional.
 */
function comment_author( $comment_ID = 0 ) {
    $author = apply_filters('comment_author', get_comment_author( $comment_ID ) );
    echo $author;
}

You can see that you van manipulate the return string given by function get_comment_author.
What you can do is add something like the following in your functions.php:

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->display_name; // this is the actual line you want to change
        } else {
            $author = __('Anonymous');
        }
    } else {
        $author = $comment->comment_author;
    }

    return $author;
});

Hope it helps!



来源:https://stackoverflow.com/questions/13798372/how-to-display-the-custom-nickname-on-wordpress-comments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!