Drupal: use user profile field in comment

By default, anonymous users can enter their homepage field when commenting on a post so that their name links to it when viewing the comment. Registered users can't and their user name links by default to their user account info.
We can change this behavior by using Drupal's built-in profile module and tweaking the submitted info in your theme's template.
We'll be using Drupal's core profile module so make sure it's enabled in admin/build/module. Next, we will need to add a homepage field. Go to admin/user/profile and add a URL field.
The category name will allow us to group similar fields together in case we have grand plans with the profile so use something that makes sense to you, like "Personal information".
The title is the name of the field and this is visible to the user. The form name is invisible to the user, it's what we'll use in the PHP code. Again, use something that makes sense to you, like "Homepage" for the title and "profile_homepage" for the form name.
Once the field has been added, it is time to attack the theme's template.php.
I use the following function to customize the submitted info for comments:
<?php
function phptemplate_comment_submitted($comment) {
return t(
'<span class="post-author">!username</span> — <span class="post-date">!datetime</span>',
array(
'!datetime' => format_date($comment->timestamp),
'!username' => theme('username', $comment)
)
);
}
?>In order to display the user's homepage link, we need to load the user profile with user_load() and then tweak the output.
If the profile module has not been enabled, or if the comment was left by an anonymous user, or if the registered user has not entered a homepage URL on his profile page, we'll just revert to a default by using the theme() function.
<?php
function phptemplate_comment_submitted($comment) {
// Load user account
$user_account = user_load(array('uid' => $comment->uid));
// Use default if module not enabled or user is not registered
// or no valid URL was entered
if ( !module_exists('profile') || $comment->uid == 0 || !valid_url($user_account->profile_homepage, TRUE) ) {
$comment_user = theme('username', $comment);
// Here the comment author is a registered user
} else {
$comment_user = l(
$user_account->name,
$user_account->profile_homepage,
array(
'attributes' => array(
'rel' => 'nofollow'
)
)
);
}
return t(
'<span class="post-author">!username</span> — <span class="post-date">!datetime</span>',
array(
'!datetime' => format_date($comment->timestamp),
'!username' => $comment_user
));
}
?>We will take somewhat of a performance hit because for each comment we are now loading the user data, but it shouldn't be all that bad.
We can do the same thing for user other profile fields, such as using a user's nick name, etc.