默認情況下,在WordPress評論中,對于登錄用戶發(fā)表的評論,會使用“公開顯示為”(display_name)字段的值作為用戶的顯示名稱。如果用戶不能修改/或者沒有修改這個“公開顯示為”選項,就會顯示用戶的登錄名(user_login)。

如果我們希望強制采用“昵稱 nickname”作為評論作者的用戶名稱,該怎么辦呢?下面我們將分析思路詳細說一下,想直接用代碼的就看最后的代碼片段即可。
通過檢查發(fā)現(xiàn),評論作者的名字和鏈接部分是通過 get_comment_author_link()函數(shù)輸出的,代碼如下:
function get_comment_author_link( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
$url = get_comment_author_url( $comment );
$author = get_comment_author( $comment );
if ( empty( $url ) || 'http://' == $url ) {
$return = $author;
} else {
$return = "<a href='$url' rel='external nofollow ugc' class='url'>$author</a>";
}
/**
* Filters the comment author's link for display.
*
* @since 1.5.0
* @since 4.1.0 The `$author` and `$comment_ID` parameters were added.
*
* @param string $return The HTML-formatted comment author link.
* Empty for an invalid URL.
* @param string $author The comment author's username.
* @param int $comment_ID The comment ID.
*/
return apply_filters( 'get_comment_author_link', $return, $author, $comment->comment_ID );
}
在代碼的第4行,我們可以看到 $author = get_comment_author( $comment );來獲取評論作者名稱,接著看 get_comment_author() 函數(shù)的代碼:
function get_comment_author( $comment_ID = 0 ) {
$comment = get_comment( $comment_ID );
if ( empty( $comment->comment_author ) ) {
$user = $comment->user_id ? get_userdata( $comment->user_id ) : false;
if ( $user ) {
$author = $user->display_name;
} else {
$author = __( 'Anonymous' );
}
} else {
$author = $comment->comment_author;
}
/**
* Filters the returned comment author name.
*
* @since 1.5.0
* @since 4.1.0 The `$comment_ID` and `$comment` parameters were added.
*
* @param string $author The comment author's username.
* @param int $comment_ID The comment ID.
* @param WP_Comment $comment The comment object.
*/
return apply_filters( 'get_comment_author', $author, $comment->comment_ID, $comment );
}
在代碼的第7行,可以看到調(diào)用的是 display_name (即“公開顯示為”)然后底部有一個鉤子:
apply_filters( 'get_comment_author', $author, $comment->comment_ID, $comment );
我們下來要做的,就是通過鉤子去修改為昵稱。將下面的代碼添加到主題的 functions.php 文件或你的插件文件中,就可以達到目的:
/**
* 將評論作者名稱顯示為昵稱
*/
function wpkj_get_comment_author_filter( $author, $comment_ID, $comment ){
$user = $comment->user_id ? get_userdata( $comment->user_id ) : false;
if ( $user ) {
$author = $user->nickname;
} else {
$author = __( 'Anonymous' );
}
return $author;
}
add_filter( 'get_comment_author', 'wpkj_get_comment_author_filter', 10, 3 );
當(dāng)然了,如果用戶沒有設(shè)置過昵稱,那還是會顯示用戶的登錄名哦。
拓展閱讀:
- https://developer.wordpress.org/reference/functions/get_comment_author/
- https://developer.wordpress.org/reference/functions/get_comment_author_link/
- WordPress 后臺用戶列表顯示用戶昵稱并支持搜索昵稱





好了,雖然是代碼小白,也經(jīng)不住我瞎折騰啊!使用這個代碼引起的普通訪客顯示成匿名問題已經(jīng)解決了,不過這似乎發(fā)不了代碼吧,我放鏈接也不知道能不能成功。先試試再說。https://www.aliwutai.com/23829.html
已經(jīng)可以實現(xiàn)注冊用戶顯示昵稱,訪客顯示他所填寫的昵稱的功能,不會把訪客填寫的昵稱統(tǒng)一轉(zhuǎn)換為匿名了。
這代碼會遇到一個問題,就是訪客評論的,會顯示成匿名了。別的都很好。當(dāng)然如果對管理員顯示成用戶名(昵稱)這樣會更好。有時候用戶留言后,不得不去后臺搜索一下看這人是誰。