search
HomeBackend DevelopmentPHP TutorialDetailed explanation of avatar cache in WordPress and cache update method in proxy, wordpress avatar_PHP tutorial

详解WordPress中的头像缓存和代理中的缓存更新方法,wordpress头像

wordpress评论中的头像是使用Gravatar的头像服务(Gravatar官方注册地址:http://en.gravatar.com),用户的缓存头像一般都是固定不变的,所以我们可以将头像缓存到本地来提高我们网站的访问速度。
我的wordpress avatar目录的头像缓存:

201631141915179.jpg (280×244)

wordpress头像缓存功能设置方法
首先是在根目录下建立一个文件夹avatar,权限755。再在里面放一个默认的头像(default.jpg),没头像的童鞋就会用默认的。代码如下:

function my_avatar( $email, $size = '32', $default = '', $alt = '') {
 $f = md5( strtolower( $email ) );
 $a = WP_CONTENT_URL . '/avatar/'. $f . $size . '.png';
 $e = WP_CONTENT_DIR . '/avatar/' . $f . $size . '.png';
 $d = WP_CONTENT_DIR . '/avatar/' . $f . '-d.png';

 if($default=='')
  $default = 'http://www.wpnoob.cn/avatar/default.jpg'; //尺寸需要改为你自己网站评论的默认头像
 
 $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}'    style="max-width:90%" />";
 return apply_filters('my_avatar', $avatar, $email, $size, $default, $alt);
}

再将以上代码添加到你主题的functions.php文件。
将获取头像地址的 get_avatar 函数替换为 my_avatar 。有个例外,functions.php评论列表函数中:

get_avatar( $comment

需要改成:

my_avatar( $comment->comment_author_email

因为my_avatar函数只能通过Email来调取用户头像,所以以上情况,需要将第一个参数改成email地址。

get_avatar函数介绍:
用上面的方法简单方便啊。 不过还有一步是要注意的。得要确认在调用头像的地方都是用get_avatar函数来完成的。一般都是了,只有以前老的theme才不是。不是的话改过来就行。

如改为:

<&#63;php
 echo get_avatar( $comment->comment_author_email, $size = '48', $default = get_bloginfo('wpurl') . '/avatar/default.jpg' ); 
&#63;>

代理(squid)中更新css/js文件缓存的方法
在wordpress添加css或者js文件,我们一般使用这四个函数来实现:

  •  wp_enqueue_script()
  •  wp_enqueue_style()
  •  wp_register_script()
  •  wp_register_style()

函数中你可以定义css/js的版本号,以便我们在对css/js文件更新时能够清楚浏览器的缓存,默认的版本号是wordpress的版本号。版本号会链接在css/js完整路径的后面,一般在版本号变更后,css/js载入的样式的完整URL也会变更,浏览器发现URL变更会重新请求css/js文件,这样就能达到载入最新的css/js文件。

但是很多代理软件(比如squid)并不支持”?“号形式的cache,我们在使用反向代理来cache我们的网站时,特别在squid3.0以后,已经开始不对带”?”号的url进行缓存了。所以我们如果要使用squid的缓存功能就必须去掉”?”,更新squid代理商的缓存只能通过修改文件名来实现。

以下我们将介绍在wordpress通过对版本号的控制来修改js/css文件名从而能够在代理软件中达到缓存的目的:
1、在我们的主题代码functions.php文件中添加如下代码:

/** 
 * Description: wordpress在代理(squid)中更新css/js文件缓存的方法
 * Author:wordpress教程网
 * Author URI: http://www.wpnoob.cn/
 */
function ds_filename_based_cache_busting( $src ) {
 // 管理员的后台css/js文件无需处理
 if ( is_admin() )
 return $src;
 //将版本号添加到文件名中已”.“号来区分
 return preg_replace(
 '/\.(js|css)\&#63;ver=(.+)$/',
 '.$2.$1',
 $src
 );
}
add_filter( 'script_loader_src', 'ds_filename_based_cache_busting' );
add_filter( 'style_loader_src', 'ds_filename_based_cache_busting' );

如果你使用的是apache服务器,在你的根目录的.htaccess文件下添加:

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /
 
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.+)\.(.+)\.(js|css)$ $1.$3 [L]
</IfModule>

 
如果你是nginx服务器配置如下:

location ~ ^(.+)\.(.+)\.(js|css)$ {
  alias $1.$3;
}&#65279;

您可能感兴趣的文章:

  • WordPress中Gravatar头像缓存到本地及相关优化的技巧

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1105380.htmlTechArticle详解WordPress中的头像缓存和代理中的缓存更新方法,wordpress头像 wordpress评论中的头像是使用Gravatar的头像服务(Gravatar官方注册地址:http...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

What is the full form of PHP?What is the full form of PHP?Apr 28, 2025 pm 04:58 PM

The article discusses PHP, detailing its full form, main uses in web development, comparison with Python and Java, and its ease of learning for beginners.

How does PHP handle form data?How does PHP handle form data?Apr 28, 2025 pm 04:57 PM

PHP handles form data using $\_POST and $\_GET superglobals, with security ensured through validation, sanitization, and secure database interactions.

What is the difference between PHP and ASP.NET?What is the difference between PHP and ASP.NET?Apr 28, 2025 pm 04:56 PM

The article compares PHP and ASP.NET, focusing on their suitability for large-scale web applications, performance differences, and security features. Both are viable for large projects, but PHP is open-source and platform-independent, while ASP.NET,

Is PHP a case-sensitive language?Is PHP a case-sensitive language?Apr 28, 2025 pm 04:55 PM

PHP's case sensitivity varies: functions are insensitive, while variables and classes are sensitive. Best practices include consistent naming and using case-insensitive functions for comparisons.

How do you redirect a page in PHP?How do you redirect a page in PHP?Apr 28, 2025 pm 04:54 PM

The article discusses various methods for page redirection in PHP, focusing on the header() function and addressing common issues like "headers already sent" errors.

Explain type hinting in PHPExplain type hinting in PHPApr 28, 2025 pm 04:52 PM

Article discusses type hinting in PHP, a feature for specifying expected data types in functions. Main issue is improving code quality and readability through type enforcement.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.