Drupal 7 – Render user profile picture programmatically @ 2

Yesterday we have talked about 2 normal ways to render the user profile picture in Drupal 7.
Drupal 7 – Render user profile picture programmatically @ 1

Unfortunately you can only get the user profile picture with default size if you have enabled the Gravatar integration moddule. i.e

$user = user_load($uid);
// This works for user with Gravatar linked
print theme('user_picture', array('account' => $user));

// This DOES NOT work for user with Gravatar linked
print theme('image_style', array('path' => $user->picture->uri, 'style_name' => '<image-style>'));

 

Seems we need something abnormal. O.o

So i spent some time on Google. Finally i could solve the problem by using the Imagecache External module.

After you have enabled the module, go to the permission settings and enable the View external images as well as Fetch external images for eligible roles. Then you can render the Gravatar picture by

$user = user_load($uid);
print theme('imagecache_external', array('path' => gravatar_get_gravatar($user ->mail), 'style_name'=> '<image-style>')); 

 

The following is a Views example which i want to show a list of users which some of them are linked to Gravatar and some don’t.
1. Add a User: Uid field and exclude it from display

2. Add a Global: PHP field (require Views PHP module)

3. Set the following code in the Global: PHP field

<?php
  $user = user_load($row->uid);
  if (empty($activity_user->picture)) {
    print theme('imagecache_external', array('path' => gravatar_get_gravatar($user ->mail), 'style_name'=> '<image-style>')); 
  } else {
    print theme('image_style', array('path' => $user ->picture->uri, 'style_name' => '<image-style>'));
  }
?>

 

Done =)

Reference:

2 thoughts on “Drupal 7 – Render user profile picture programmatically @ 2”

  1. There’s a slight problem the $user = user_load($uid), actually logs in the user with the UID from the current path, or switches the logged in UID to that UID. Not sure if this is error in code, or that’s just the way this code behaves when it’s used in Views Header

    <?
    $user = user_load($uid);
    // This works for user with Gravatar linked
    print theme('image_style', array('path' => $user->picture->uri, 'style_name' => '<image-style>')); ?>
    

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.