由于 Gravatar 头像被墙,导致头像加载很慢,因此在网上搜索“wordpress头像缓存优化”的方法,结果搜到的基本都是不太有效的,甚至是不可用的,偶然在露兜博客看到了一个方法,试用后,感觉非常完美,在此就分享出来供大家借鉴一二。
优化后的缓存代码
废话不多说,直接上代码:
- /**
- * WordPress头像本地化缓存最有效方法 – 龙笑天下
- * http://www.ilxtx.com/wordpress-gravatar-local-cache.html
- */
- function my_avatar( $email = ‘[email protected]’, $size = ’32’, $default = ”, $alt = ”) {
- // 设置$email默认值为一个不存在的邮箱,如:[email protected]
- // 防止空的$email导致出错
- $f = md5( strtolower( $email ) );
- // 以下代码将头像缓存到wp-content目录下
- $a = WP_CONTENT_URL . ‘/avatar/’. $f . $size . ‘.png’;
- $e = WP_CONTENT_DIR . ‘/avatar/’ . $f . $size . ‘.png’;
- $d = WP_CONTENT_DIR . ‘/avatar/’ . $f . ‘-d.png’;
- // 如果要将头像缓存到当前主题目录下,请将11-13行代码改成:
- // $a = get_bloginfo(‘template_url’) . ‘/avatar/’. $f . $size . ‘.png’;
- // $e = get_template_directory() . ‘/avatar/’ . $f . $size . ‘.png’;
- // $d = get_template_directory() . ‘/avatar/’ . $f . ‘-d.png’;
- if($default==”)
- $default = ‘http://www.ilxtx.com/wp-content/themes/lxtx/images/gravatar.png’;
- $t = 2592000; // 缓存有效期30天, 这里单位:秒
- if ( !is_file($e) || (time() – filemtime($e)) > $t ) {
- if ( !is_file($d) || (time() – filemtime($d)) > $t ) {
- // 验证是否有头像
- $uri = ‘http://www.gravatar.com/avatar/’ . $f . ‘?d=404’;
- $headers = @get_headers($uri);
- if (!preg_match(“|200|”, $headers[0])) {
- // 没有头像,则新建一个空白文件作为标记
- $handle = fopen($d, ‘w’);
- fclose($handle);
- $a = $default;
- }
- else {
- // 有头像且不存在则更新
- $r = get_option(‘avatar_rating’);
- $g = ‘http://www.gravatar.com/avatar/’. $f. ‘?s=’. $size. ‘&r=’ . $r;
- copy($g, $e);
- }
- }
- else {
- $a = $default;
- }
- }
- $avatar = “<img alt='{$alt}’ src='{$a}’ class=’avatar avatar-{$size} photo’ height='{$size}’ width='{$size}’ />”;
- return apply_filters(‘my_avatar’, $avatar, $email, $size, $default, $alt);
- }
使用方法
- 重要:在 wp-content 目录下新建一个目录,命名为 avatar,权限设为 755;如果选择头像缓存到当前主题下,请在当前主题目录下,请在当前主题目录下新建一个目录,命名为 avatar,权限设为 755;
- 将以上代码放到当前主题 functions.php 的最后一个 ?> 的前面;
- 以上代码第 20 行换成你本地的默认头像地址;
- 这里默认头像大小是 32*32,可在以上代码第 1 行更改;
- 在需要使用 Gavatar 头像的地方调用 my_avatar 函数即可。一般在主题所有文件中,将 get_avatar 函数替换为 my_avatar 。有个例外,functions.php评论列表函数中:get_avatar( $comment 需要改为 my_avatar( $comment->comment_author_email。因为 my_avatar 函数只能通过 Email 来调取用户头像,所以以上情况,需要将第一个参数改成 email 地址。
友情提示
这个新的头像调用函数 my_avatar 可以传递 alt 参数,因此可以不必另行使用其他函数来给这个 Gravatar 头像加 alt 标签了。比如评论者头像的输入可以参考以下代码:
- <?php echo my_avatar( $comment->comment_author_email,50,$default=”,$comment->comment_author); ?>
其中 50 表示这个头像的大小是 50*50,alt 属性值就是评论者昵称。