Q: 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 ImageCache and respects the default user picture?
A: 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 ImageCache 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 ImageCache preset to the picture before it's displayed.
(0) Create an ImageCache 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 ImageCache 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:
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 ImageCache presets in different situations, then all would have to do is add a new 'display' to the view and override the picture field's ImageCache settings...
Did you find this post helpful? If so, we'd love to hear from you in our comments! If you found it really useful we'd love a link from your Blog-Web Site, to us!
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!!