I'm setting up a wordpress website where users can comment based on user roles.
I would like to link the name of the comment author to their personal profile page (site url/profile/username)
.
I have almost 0 knowledge about PHP, and I know a bit of CSS. I have tried a couple of different code snippets in my child theme function.php
, but none of them seem to work properly.
The following snippet for example, only links the comment author name to site url/profile/user
ID, but I would like it to be site 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');
I expect to get the username and not the user ID. I've tried some changes in the snippet but nothing seems to work. I'd like to know what I am doing wrong and what I can do to improve it. Thanks in advance.
You can make use of the inbuilt get_userdata function to find out the comment author username. I have explained the added coded in comments as suffix.
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');