我正在尝试 link 评论作者姓名到站点 url/profile/author 用户名

I am trying to link the comment author name to site url/profile/author username

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

我对PHP的了解几乎为0,对CSS略知一二。我在我的子主题 function.php 中尝试了几个不同的代码片段,但其中 none 似乎可以正常工作。 以下代码段为例,只有 links 评论作者姓名到站点 url/profile/user ID,但我希望它是站点 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');