I added a country field to users and want to show it below the username on comments (in the Bartik theme). How can I load that field into the bartik_preprocess_comment() function?


Drupal already loads the user object. You can see the user object on that function:

function bartik_preprocess_comment($variables) {
  $user = $variables['user'];
  // Full load user
  $user = user_load($user->uid);
  // Now access your field
  $country = field_get_items('user', $user, 'field_country');
  if ($country) {
    $variables['author_country'] = $country[0]['safe_value'];
  else {
    $variables['author_country'] = '';
  // On your comment.tpl.php using $author_country
  • fantastic! Thanks so much for the detailed help!!! For future reference here are the 2 lines to get the country name and a icon of the country flag: $variables['user_country_name'] = $country[0]['safe']; $variables['user_country_flag'] = theme('countryicons_icon', array('code' => $country[0]['iso2'], 'iconset' => 'shiny'));
    – uwe
    Sep 15 '11 at 4:07
  • $variables['user']->uid is the user ID for the user who is viewing the comment, not the user who created the comment. This code is showing the flag of the user who is viewing the comment, not the comment author. See the other answer. It's a shame users need to read two answers, and the comments for the first answer to understand which answer is correct.
    – apaderno
    May 8 '14 at 16:26

template_preprocess_comment(), the preprocess function that is called before MODULE_preprocess_HOOK() and THEME_preprocess_HOOK(), uses $variables['user'], but from the code it is using, I take that variable contains the user object for the user who is viewing the comment; differently the CSS class it is adding would not be "comment-by-viewer" ($comment->uid is the user ID for the author of the comment).

if ($comment->uid === $variables['user']->uid) {
  $variables['classes_array'][] = 'comment-by-viewer';

If you want to load any field associated with the user who created the comment, you can use $comment->uid, and pass it to user_load(). In fact, template_preprocess_comment() contains the following code, which means that $comment->uid is the user ID of the user who created the comment; once compared with $variables['node']->uid, the code is able to say that the comment was created by the node author.

if ($comment->uid == $variables['node']->uid) {
  $variables['classes_array'][] = 'comment-by-node-author';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.