修改 WordPress 主题适配 FastCGI_Cache 静态化缓存

WordPress 网站博客使用 Nginx FastCGI_Cache 静态化缓存加速,配合 Memcached 缓存减少数据库查询,效果还不错。折腾时注意 FastCGI_Cache 可能会把评论者信息和登陆信息缓存,上线前 WordPress 主题一定要测试适配好。

修改 WordPress 主题适配 FastCGI_Cache 静态化缓存插图

WordPress 主题如何适配 FastCGI_Cache 静态化缓存?

WordPress 启用 FastCGI_Cache 静态化缓存,可能会带出一些问题,比如前面所说 FastCGI_Cache 可能会缓存评论者名称和邮箱信息;如果在登陆状态回复评论,会缓存登陆界面;WP-PostViews 不计数……下面记录一下折腾过程,有需要参考一下。

風冷無霜 0xo.net|uxtt.com|867755.com…
「修改 WordPress 主题适配 FastCGI_Cache 静态化缓存:https://bdkp.net/20」

WordPress 让管理员在前台匿名以避免 CDN/静态缓存

作者:成航先森,这个可以避免把管理员访问网页被缓存。

温馨提示:若前面 登录用户和评论过的用户不展示缓存 规则 配置正确,且生效,不需要使用此处代码。

/*
** 让管理员在前台访问匿名
** http://www.capjsj.cn/make_known_users_anonymous.html
*/
function make_known_users_anonymous() {
	global $current_user;
	if(!is_admin() && $_GET['preview'] != 'true'){
		$current_user = array(
			'user_login' => '',
			'user_email' =>'',
			'user_level' => '',
			'user_firstname' => '',
			'user_lastname' => '',
			'display_name' => '',
			'ID' => '',
			'user_url' => '',
		);
	}
	return $current_user;
}
add_action( 'init', 'make_known_users_anonymous' );

修改 WordPress 主题评论框表单 适配 FastCGI_Cache 静态化缓存

ajax 提交评论部分可能会有设置 cookies 记住评论者信息代码:

風冷無霜 0xo.net|uxtt.com|867755.com…
「修改 WordPress 主题适配 FastCGI_Cache 静态化缓存:https://bdkp.net/20」

$user = wp_get_current_user();
do_action('set_comment_cookies', $comment, $user);

亲测,把这两行注释掉,对所有用户缓存情况下,还是会把评论者信息缓存,展示给其他用户。

因为评论表单代码可能这样子:

<div id="comment-author-info">
	<p class="comment-form-author">
		<input type="text" name="author" placeholder="昵称<?php if ($req) echo "(必填)"; ?>" id="author" class="commenttext" value="<?php echo $comment_author; ?>" tabindex="1" />
	</p>
	<p class="comment-form-email">
		<input type="text" name="email" placeholder="邮箱<?php if ($req) echo "(必填)"; ?>" id="email" class="commenttext" value="<?php echo $comment_author_email; ?>" tabindex="2" />
	</p>
	<p class="comment-form-url">
		<input type="text" name="url" placeholder="网址" id="url" class="commenttext" value="<?php echo $comment_author_url; ?>" tabindex="3" />
	</p>
</div>

把表单中 value="<?php echo $comment_******; ?>" 直接删除或者改成 value=”” 也许就好了。

風冷無霜 0xo.net|uxtt.com|867755.com…
「修改 WordPress 主题适配 FastCGI_Cache 静态化缓存:https://bdkp.net/20」

FastCGI_Cache 静态化缓存导致 WP-Postviews 浏览数不更新怎么解决?

WordPress 使用 FastCGI_Cache 页面静态化后,原本 php 统计浏览数会失效,导致浏览数不更新。解决方法:CDN 后用 Ajax 动态提交、显示文章阅读量,cookies 避免重复刷新

注:WP-Postviews(文章浏览数)代码精简版同样适用。

在 footer.php 中添加 ajax 代码

注意需要将前台显示访问量标签 ID 或 class 名称须与主题匹配。

風冷無霜 0xo.net|uxtt.com|867755.com…
「修改 WordPress 主题适配 FastCGI_Cache 静态化缓存:https://bdkp.net/20」

<?php 
  if( defined( 'FastCGI_Cache' ) && FastCGI_Cache ): // CDN、开缓存 wp-config.php 开启缓存  ?>
    <script type= "text/javascript" >
      //http://cn.voidcc.com/question/p-rymvrgdr-rc.html
      function intlFormat(num) { 
        return new Intl.NumberFormat().format(Math.round(num*10)/10); 
      } 
      function makeFriendly(num) { 
        if(num >= 1000000) 
        return intlFormat(num/1000000)+'M'; 
        if(num >= 1000) 
        return intlFormat(num/1000)+'k'; 
        return intlFormat(num); 
      }
      function GetCookie(sName) {
        var arr = document.cookie.match(new RegExp("(^| )"+sName+"=([^;]*)(;|$)"));
        if(arr !=null){return unescape(arr[2])};
        return null;
      }
      var postviews_cook=GetCookie("postviews-<?php the_ID();?>");
      if ( postviews_cook == null ){
        jQuery.ajax({ type:'POST', url: "<?php echo admin_url('admin-ajax.php');?>" , data:"postviews_id=<?php the_ID();?>&action=postviews",
        cache:false,success: function(postviews_count){ jQuery("#main #post-<?php the_ID();?> .views").text('Views:' + makeFriendly( postviews_cook ) );document.cookie="postviews-<?php the_ID();?>=" + postviews_count;} }); 
      } else {
        jQuery("#main #post-<?php the_ID();?> .views").text('Views:' + makeFriendly( postviews_cook ) );
      };
    </script>
<?php endif; ?>

主题 functions.php 添加代码

if( defined( 'FastCGI_Cache' ) && FastCGI_Cache ){ // CDN、开缓存 wp-config.php 开启缓存
  /*
  * 缓存时更新浏览量-有缓存
  * http://www.capjsj.cn/ajax_cookies_views.html
  */
  function postviews_cache(){
    if( empty( $_POST['postviews_id'] ) ) return;

    $post_ID = $_POST['postviews_id'];
    if( $post_ID > 0 ) {
      $post_views = (int)get_post_meta($post_ID, 'views', true);
      update_post_meta($post_ID, 'views', ( $post_views + 1 ));
      echo ( $post_views + 1 );
      exit();
    }
  }
  add_action( 'wp_ajax_nopriv_postviews', 'postviews_cache' );
  add_action( 'wp_ajax_postviews', 'postviews_cache' );
}

修改 wp-config.php 配置

加入下面代码,然后重启 php 即可:

define('FastCGI_Cache', true);

如使用 WP-Postviews 插件,wp-config.php 中,加入下面这行代码:

define('WP_CACHE', true);

然后在 WP-Postviews 插件选项中启用「使用 AJAX 更新浏览量」即可。

WordPress 开启 FastCGI_Cache 静态化缓存后如何记住评论者信息?

前面一顿操作,如无意外,WordPress 已经记不住评论用户信息,这样访客每次评论都需要填写信息,很不友好。

解决方法:WordPress 记住评论用户信息的 js 版本,直接操作 cookie 无视缓存、解决 JS 操作 Cookies 出现的乱码问题,修复 WordPress 评论乱码

代码

//设置 Cookie
function SetCookie(sName, sValue,iExpireDays) {
	if (iExpireDays){
		var dExpire = new Date();
		dExpire.setTime(dExpire.getTime()+parseInt(iExpireDays*24*60*60*1000));
		document.cookie = sName + "=" + escape(sValue) + "; expires=" + dExpire.toGMTString()+ "; path=/;domain=.123.com";
	}
	else{
		document.cookie = sName + "=" + escape(sValue)+ "; path=/;domain=.123.com";
	}
}
// 目的:    返回 Cookie
function GetCookie(sName) {
	var arr = document.cookie.match(new RegExp("(^| )"+sName+"=([^;]*)(;|$)"));
	if(arr !=null){return unescape(arr[2])};
	return null;
 
}
//加载用户信息
function LoadRememberInfo() {
	var strName=GetCookie("author");
	var strEmail=GetCookie("email");
	var strHomePage=GetCookie("url");
	var bolRemember=GetCookie("chkRemember");
    var a_vlaue= document.getElementById("author");
    if (a_vlaue != null){
	    if(bolRemember=="true"){
                    //通过 decodeURIComponent 对内容解码
		    if(strName){document.getElementById("author").value=decodeURIComponent(strName);};
		    if(strEmail){document.getElementById("email").value=strEmail;};
                     //通过 decodeURIComponent 对内容解码
		    if(strHomePage){document.getElementById("url").value=decodeURIComponent(strHomePage);};
		    if(bolRemember){document.getElementById("saveme").checked=bolRemember;};
	    }
 
	    if(GetCookie("username")){
		    document.getElementById("author").value=unescape(GetCookie("username"));
	    }
    }	
}
//通过 jQuery ready 在页面加载时自动从 cookies 中载入已保存的用户信息
jQuery(document).ready(function($){
       LoadRememberInfo();
//给评论提交按钮绑定信息保存函数
    $("#respond #submit").click(function(){
       SaveRememberInfo();
    });
//给评论重置按钮绑定信息移除函数
    $("#respond #reset").click(function(){
        RemoveRememberInfo();
    });
});
//保存信息函数
function SaveRememberInfo() {
	var strName=document.getElementById("author").value;
	var strEmail=document.getElementById("email").value;
	var strHomePage=document.getElementById("url").value;
	var bolRemember=document.getElementById("saveme").checked;
        //通过 encodeURIComponent 对内容进行 url 编码
	SetCookie("author",encodeURIComponent(strName),365);
	SetCookie("email",strEmail,365);
        //通过 encodeURIComponent 对内容进行 url 编码
	SetCookie("url",encodeURIComponent(strHomePage),365);
	SetCookie("chkRemember",bolRemember,365);
 
}
//移除信息函数
function RemoveRememberInfo() {
	SetCookie("author",'',365);
	SetCookie("email",'',365);
	SetCookie("url",'',365);
	SetCookie("chkRemember",'false',365);
}

代码中有两处 domain=.123.com,一定要更改成自己博客域名。

将代码加入到 WordPress 主题 js 文件中即可,比如加入到 comments-ajax.js 最后。如果没有 ajax 评论,就没有 comments-ajax.js,可以将代码保存为 saveinfo.js ,然后引入即可。

修改 comments.php

编辑主题 comments.php 文件,找到提交留言按钮代码,在合适位置添加勾选框:

<input type="checkbox" id="saveme" value="saveme" checked="checked" title="记住我,下次回复时无需重新输入个人信息。" /><label for="comment_mail_notify"> 记住我</label>

添加后代码,仅供参考,需根据实际修改:

.... 以上省略....
<p class="form-submit">
	<input type="checkbox" id="saveme" value="saveme" checked="checked" title="记住我,下次回复时无需重新输入个人信息。" /><label for="comment_mail_notify"> 记住我</label>
	<input id="submit" name="submit" type="submit" tabindex="5" value="发表留言 (Ctrl+Enter)"/>
	<?php comment_id_fields(); do_action('comment_form', $post->ID); ?>
</p>
.... 以下省略....

WordPress 回复评论自动添加 @评论者

作者:露兜

这个非必需,博主这里启用 444 级评论嵌套,不过只显示 2 级样式,不加上 @评论者,有时候可能不知道谁回复谁。

在当前主题 functions.php 中添加以下代码(会直接将 @ 信息写入数据库):

// 评论添加 @,by Ludou
function ludou_comment_add_at( $commentdata ) {
  if( $commentdata['comment_parent'] > 0) {
    $commentdata['comment_content'] = '@<a href="#comment-' . $commentdata['comment_parent'] . '">'.get_comment_author( $commentdata['comment_parent'] ) . '</a> ' . $commentdata['comment_content'];
  }

  return $commentdata;
}
add_action( 'preprocess_comment' , 'ludou_comment_add_at', 20);

如果你不想将 @评论者 写入数据库,可以使用下面的代码:

// 评论添加 @,by Ludou
function ludou_comment_add_at( $comment_text, $comment = '') {
  if( $comment->comment_parent > 0) {
    $comment_text = '@<a href="#comment-' . $comment->comment_parent . '">'.get_comment_author( $comment->comment_parent ) . '</a> ' . $comment_text;
  }

  return $comment_text;
}
add_filter( 'comment_text' , 'ludou_comment_add_at', 20, 2);

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注