Wordpress多用户系统 站点及文章访问量缓存方法

/**
 * 博客、文章访问量缓存
 * useage: makeCount(int 博客ID [, int 文章ID [, int 更新间隔(1800s) [, int 博客访问量 [, int 文章访问量]]]] )
 * @author MrAsong 2012-04-26
 */
function makeCount($bid=1, $pid=0, $update_interval=1800, $num_home=50, $num_post=15){
	global $wpdb;

	$count_file = ABSPATH . 'cache/blogcount_'.$bid.'.js' ;

	if( $json = @file_get_contents($count_file) ){
		$c = json_decode($json,true); //获取数据
	}else{ //如果不存在,创建count文件
		$c = array(
			'create'    => time(), //上次更新时间
			'blogcount' => 0 
		);
	}
	
	if( $pid == 0 ){ // 判断是否为首页
		$c['blogcount'] = $c['blogcount'] + 1 ; //count+1

		if( $c['blogcount'] >= $num_home && (time()-$c['create']) > $update_interval ){//更新博客访问量
			$sql = "UPDATE $wpdb->blogs SET count=count+{$c['blogcount']} WHERE blog_id=$bid";
			$wpdb->query($sql);
			$c['create'] = time();
			$c['blogcount'] = 0;
		}
	}else{
		$c['post'][$pid]['c'] = isset($c['post'][$pid]['c']) ? ($c['post'][$pid]['c'] + 1) : 1 ;
		$c['post'][$pid]['t'] = isset($c['post'][$pid]['t']) ? $c['post'][$pid]['t'] : time();	
		if( $c['post'][$pid]['c'] >= $num_post && (time()-$c['post'][$pid]['t']) > $update_interval ){//更新博客访问量
			$sql = "UPDATE $wpdb->posts SET count=count+{$c['post'][$pid]} WHERE ID=$pid";
			$wpdb->query($sql);
			unset($c['post'][$pid]); //删除此元组
		}
	}
	
	if($fp = @fopen($count_file, 'wb')) {
		@fwrite( $fp, json_encode($c) );//写入json
		fclose($fp);
	}

}

添加新评论