[b]Q:[/b] How can I theme and display a user picture or avatar in a page, block or content template with PHP in a way that works with [url=http://drupal.org/project/imagecache]ImageCache[/url] and respects the default user picture?
[b]A:[/b] One easy way to embed a user picture into your content is to create a user view to output the picture and then just embed this view into your content by calling
views_embed_view() passing in the user id as an argument.
Recently, the web design I was working on for one of our Cork clients called for the insertion of user avatars directly into some page content. It seems that there are loads of ways of using PHP to embed a user picture, for example, suggestions and code snippets can be found here:
However I found all of this quite confusing and it seems that you have to manually handle the display of the default user picture in the cases where user has not configured an avatar of their own. Also, I wanted to apply [url=http://drupal.org/project/imagecache]ImageCache[/url] presets to my user images and it seems that would require further coding....
So as my head was spinning, I decided to ditch all of this confusion and take a different tack. I hatched a plan to create a view which would take the target user id as an argument and would output just the user's picture. To display the view (and hence the user avatar) all I would have to do is call
views_embed_view() passing in the user id.
The advantage of this approach is that Views will automatically display the default user picture (if necessary) and also allows you to easily apply an [url=http://drupal.org/project/imagecache]ImageCache[/url] preset to the picture before it's displayed.
(0) Create an [url=http://drupal.org/project/imagecache]ImageCache[/url] preset for the user avatar (if you want to user one that is...)
(1) Create a 'user' view
(2) Add a field - User: Picture
(3) Remove the field label and choose an [url=http://drupal.org/project/imagecache]ImageCache[/url] preset if required
(3) Add an Argument - User: Uid
(4) Test and Save your view - type a valid uid into the 'Live Preview' arguments box and hit the preview button, if you see a user picture of the right size you're in business!
Now you're ready to embed the view into your content. Let's say that you called your view 'user_picture', and that have the target user's user id (
$uid), then all you have to do to display the picture is:
print views_embed_view('user_picture', 'default', $uid);
Thankfully it worked like a treat for me and I don't have to worry about all those head-wrecking and sometimes contradictory PHP snippets!!
If you wanted to employ different [url=http://drupal.org/project/imagecache]ImageCache[/url] presets in different situations, then all would have to do is add a new 'display' to the view and override the picture field's [url=http://drupal.org/project/imagecache]ImageCache[/url] settings...
Rock on Views!