4

I'm displaying the userpicture on a node with this code here:

<?php
    $user_load = user_load($node->uid);
    $imgtag = theme('imagecache', 'avatar_node', $user_load->picture, $user_load->name, $user_load->name);
    $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
    print l($imgtag, 'u/'.$user_load->name, $attributes);
?>

This works great, except if the user doesn't have a picture, in which case it looks strange.

How do I load the default picture if the user doesn't have a picture. I don't believe I have access to $picture in this block.

Thanks in advance.

Jourkey
  • 33,710
  • 23
  • 62
  • 78

3 Answers3

6

    $user_load = user_load($node->uid);
    $picture = $user_load->picture ? $user_load->picture : variable_get('user_picture_default', ''); // 
    $imgtag = theme('imagecache', 'avatar_node', $picture, $user_load->name, $user_load->name); 
    $attributes = array('attributes' => array('title' => t('View user profile.')), 'html' => TRUE);
    print l($imgtag, 'u/'.$user_load->name, $attributes);

if you copy default picture to files directory, you can determine it via http://api.drupal.org/api/function/file_directory_path/6

Jeremy French
  • 11,707
  • 6
  • 46
  • 71
Nikit
  • 5,128
  • 19
  • 31
  • Rather than manual path to default pic, isn't there a way to get the default pic set in drupal user settings? Thanks. – Jourkey Jan 11 '10 at 08:25
  • 2
    variable_get('user_picture_default', '') will get the default picture URL. (edited answer to include this) – Jeremy French Jan 11 '10 at 10:13
2

This is what I'm using for a similar situation:

      if (!empty($user->picture) && file_exists($user->picture)) {
        $picture = file_create_url($user->picture);
      }
      else if (variable_get('user_picture_default', '')) {
        $picture = variable_get('user_picture_default', '');
      }

      if (isset($picture)) {

        $alt = t("@user's picture", array('@user' => $user->name ? $user->name : variable_get('anonymous', t('Anonymous'))));
        $picture = theme('image', $picture, $alt, $alt, '', FALSE);
        if (!empty($user->uid) && user_access('access user profiles')) {
          $attributes = array(
            'attributes' => array('title' => t('View user profile.')),
            'html' => TRUE,
          );
          echo l($picture, "user/$user->uid", $attributes);
        }
      }

It is adapted from http://api.drupal.org/api/drupal/modules%21user%21user.module/function/template_preprocess_user_picture/6

Rimu Atkinson
  • 775
  • 4
  • 15
1

In Drupal 7 I use:

global $user;
file_create_url( file_load($user->picture)->uri)
Ray Hulha
  • 10,701
  • 5
  • 53
  • 53