【问题标题】:Drupal: Checking to see if User Has PictureDrupal:检查用户是否有图片
【发布时间】:2025-12-03 00:25:01
【问题描述】:

我在这里使用此代码在节点上显示用户图片:

<?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);
?>

这很好用,除非用户没有图片,在这种情况下看起来很奇怪。

如果用户没有图片,我如何加载默认图片。 我不相信我可以访问此块中的 $picture。

提前致谢。

【问题讨论】:

    标签: drupal image avatar


    【解决方案1】:

    在 Drupal 7 中我使用:

    global $user;
    file_create_url( file_load($user->picture)->uri)
    

    【讨论】:

      【解决方案2】:

      这是我在类似情况下使用的:

            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);
              }
            }
      

      改编自http://api.drupal.org/api/drupal/modules%21user%21user.module/function/template_preprocess_user_picture/6

      【讨论】:

        【解决方案3】:
        
            $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);
        

        如果将默认图片复制到files目录,可以通过http://api.drupal.org/api/function/file_directory_path/6确定

        【讨论】:

        • 不是手动路径到默认图片,有没有办法在drupal用户设置中设置默认图片?谢谢。
        • variable_get('user_picture_default', '') 将获取默认图片 URL。 (编辑后的答案包括这个)