使用php实现Gravatar - 如何将邮件地址连接到“$ email”变量

时间:2012-10-13 16:57:46

标签: php drupal drupal-7 gravatar

Gravatar在下面的页面中描述了它的php实现:

https://en.gravatar.com/site/implement/images/php/

我正在尝试使用此代码在Drupal的用户配置文件和用户图片中实现它。

我创建了一个预处理函数来启用user-profile.tpl.php中的打印电子邮件地址

function THEMENAME_preprocess_user_profile(&$variables) {
    $account = $variables['elements']['#account'];
    foreach (element_children($variables['elements']) as $key) {
        $variables['user_profile'][$key] = $variables['elements'][$key];
    }
    $variables['user_profile']['mail'] = $account->mail;
    field_attach_preprocess('user', $account, $variables['elements'], $variables);
}

将代码添加到 user-profile.tpl.php

print render($user_profile['mail']);

此代码可以正常运行 - 它在用户配置文件中显示邮件地址。现在我需要使用该地址在配置文件和用户图片中创建gravatars。

我已经尝试连接Gravatar网站上的教程和此代码,但没有成功。这是代码(我尝试了至少20种不同的组合):

$email = "['user_profile']['mail']";
$default = "http://www.somewhere.com/homestar.jpg";
$size = 40;
function get_gravatar( $email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array() ) {
        $url = 'http://www.gravatar.com/avatar/';
        $url .= md5( strtolower( trim( $email ) ) );
        $url .= "?s=$s&d=$d&r=$r";
        if ( $img ) {
            $url = '<img src="' . $url . '"';
            foreach ( $atts as $key => $val )
                $url .= ' ' . $key . '="' . $val . '"';
            $url .= ' />';
        }
        return $url;
    }

据我了解,问题出在这一行:

$email = "['user_profile']['mail']";

我做错了什么,在这一行中引号之间的正确表达是什么?

1 个答案:

答案 0 :(得分:2)

问题是基本的PHP语法,$variables['user_profile']['mail']用于对嵌套数组的简单访问(即数组中的数组。此外,如果print render($user_profile['mail']);显示用户电子邮件地址,{{ 1}}显然是传递给自定义$user_profile['mail']功能的电子邮件地址。

get_gravatar()

我建议使用Gravatar Integration module而不是编写自己的实现。