我正在尝试将评论作者姓名链接到站点网址/个人资料/作者用户名



我正在建立一个wordpress网站,用户可以根据用户角色发表评论。 我想将评论作者的姓名链接到他们的个人资料页面(site url/profile/username)

我对PHP几乎为零,而且我知道一点CSS。我已经在我的子主题function.php中尝试了几个不同的代码片段,但它们似乎都无法正常工作。 例如,以下代码片段仅将评论作者姓名链接到站点url/profile/userID,但我希望它是站点url/profile/username

function force_comment_author_url($comment)
{
// does the comment have a valid author URL?
$no_url = !$comment->comment_author_url || $comment->comment_author_url == 'http://';
if ($comment->user_id && $no_url) {
// comment was written by a registered user but with no author URL
$comment->comment_author_url = 'http://www.founderslair.com/profile/' . $comment->user_id;
}
return $comment;
}
add_filter('get_comment', 'force_comment_author_url');

我希望获得用户名而不是用户 ID。我已经尝试了代码片段中的一些更改,但似乎没有任何效果。我想知道我做错了什么,我能做些什么来改进它。 提前谢谢。

您可以使用内置的get_userdata功能来查找评论作者用户名。我已经将注释中添加的编码解释为后缀。

function force_comment_author_url($comment)
{
// does the comment have a valid author URL?
$no_url = !$comment->comment_author_url || $comment->comment_author_url == 'http://';
if ($comment->user_id && $no_url) {

$c_userdata = get_userdata( $comment->user_id ); // Add - Get the userdata from the get_userdata() function and store in the variable c_userdata
$c_username = $c_userdata->user_login; // Add - Get the name from the $c_userdata
// comment was written by a registered user but with no author URL
$comment->comment_author_url = 'http://www.founderslair.com/profile/' . $c_username; // Replace - user_id with username variable.
}
return $comment;
}
add_filter('get_comment', 'force_comment_author_url');

最新更新