如何在Wordpress评论中显示“自定义昵称”?

时间:2012-12-10 09:42:16

标签: wordpress

发布评论时,它始终打印在“用户CMS”区域设置的不可编辑昵称。 我想打印自定义昵称(可以通过下拉列表选择的昵称)。

我实际上使用comment_author_link();并且似​​乎还不够。我该怎么办?

1 个答案:

答案 0 :(得分:1)

WordPress使用以下代码检索当前评论的作者:

/**
 * 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;
}

你可以看到你操纵函数get_comment_author给出的返回字符串 您可以做的是在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;
});

希望它有所帮助!