1

Because my site requires user pictures to be approved, the default Drupal user picture is not suitable.

Instead, I want to show a picture from a field in each user's profile as the user's profile picture.

The field is "field_profile_picture".

The image style is "profile_picture".

Based on this tutorial, I put the following code in user-picture.tpl.php in my theme's templates folder:

if (!empty($user->field_profile_picture['und'][0]['filename'])) {
  echo theme('image_style', array('style_name' => 'profile_pic', 'path' => file_build_uri($user->field_profile_picture['und'][0]['filename'])));
}

This doesn't result in any PHP errors but no picture is displayed. It appears that field_acc_profile_picture is evaluating as empty because even if I put a print "Hello world"; inside the {} it doesn't appear. However, I am sure that the field has a value because I can see the picture displayed in views.

1 Answer 1

5

I don't think $user->field_profile_picture['und'][0]['filename'] would be set by default, you normally only get the fid column (this does vary depending on context, but you should always get the fid column either way).

This sort of code always works for me:

if (!empty($user->field_profile_picture[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($user->field_profile_picture[LANGUAGE_NONE][0]['fid']);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
  echo theme('image_style', array('style_name' => 'profile_picture', 'path' => $file->uri));
}

If you're worried about the extra overhead involved with potentially loading the file twice, don't be, Drupal caches the object the first time round.

It the above doesn't work it's likely that the $user object is not fully loaded and so the fields haven't been attached. If that's the case, load the user like this:

$account = user_load($user->uid);

And then use the $account object to test for the field value.

3
  • Thank you so much! I needed to add $account = user_load($user->uid); to get it to work properly. Mar 30, 2012 at 14:04
  • 1
    One quick addition: I actually needed to load $account as $account = user_load($account->uid); Otherwise, when displaying the user pictures in the privatemsg module it will show the logged-in user's picture for all users. Mar 30, 2012 at 14:11
  • Any update on this? I can't get it to work at all. :)
    – user14666
    May 8, 2015 at 17:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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