要实现这个功能我们需要使用记录cookie的方式来实现
首先我们需要一个添加cookie的函数,有效时间为24小时。
在主题”function.php”添加以下代码:
//添加cookie function cwtk_add_cookie($post_id){ $COOKNAME = 'wp_view'; //cookie名称 $TIME = 3600 * 24; $PATH = '/'; $id = $post_id; $expire = time() + $TIME; //cookie有效期 if(isset($_COOKIE[$COOKNAME])) $cookie = $_COOKIE[$COOKNAME]; //获取cookie else $cookie = ''; if(empty($cookie)){ //如果没有cookie setcookie($COOKNAME, $id, $expire, $PATH); }else{ //用a分割成数组 $list = explode('a', $cookie); //如果已经存在本文的id if(!in_array($id, $list)){ setcookie($COOKNAME, $cookie.'a'.$id, $expire, $PATH); } } }
我们需还要查看文章页面是否已经添加过cookie
//查看cookie function check_cookie($post){ $COOKNAME = 'wp_view'; if(isset($_COOKIE[$COOKNAME])) $cookie = $_COOKIE[$COOKNAME]; else return false; $id = $post->ID; if(empty($id)){ return false; } if(!empty($cookie)){ $list = explode('a', $cookie); if(!empty($list) && in_array($id, $list)){ return true; } } return false; }
接下来我们需要添加统计代码,如果没有cookie就计次+1有就跳过,代码如下:
function post_views_record() { if (is_singular()) { global $post; $post_ID = $post->ID; if(check_cookie($post)) return; if(is_int($post)) { $post = get_post($post); } if(!wp_is_post_revision($post)) { if ($post_ID) { $post_views = (int) get_post_meta($post_ID, 'views', true); //统计所有人 $should_count = true; //排除机器人 $bots = array('Google Bot' => 'googlebot', 'Google Bot' => 'google', 'MSN' => 'msnbot', 'Alex' => 'ia_archiver', 'Lycos' => 'lycos', 'Ask Jeeves' => 'jeeves', 'Altavista' => 'scooter', 'AllTheWeb' => 'fast-webcrawler', 'Inktomi' => 'slurp@inktomi', 'Turnitin.com' => 'turnitinbot', 'Technorati' => 'technorati', 'Yahoo' => 'yahoo', 'Findexa' => 'findexa', 'NextLinks' => 'findlinks', 'Gais' => 'gaisbo', 'WiseNut' => 'zyborg', 'WhoisSource' => 'surveybot', 'Bloglines' => 'bloglines', 'BlogSearch' => 'blogsearch', 'PubSub' => 'pubsub', 'Syndic8' => 'syndic8', 'RadioUserland' => 'userland', 'Gigabot' => 'gigabot', 'Become.com' => 'become.com','Baidu Bot'=>'Baiduspider'); $useragent = $_SERVER['HTTP_USER_AGENT']; foreach ($bots as $name => $lookfor) { if (stristr($useragent, $lookfor) !== false) { $should_count = false; break; } } if($should_count) { if (!update_post_meta($post_ID, 'views', ($post_views + 1))) { add_post_meta($post_ID, 'views', 1, true); } } } } } }
我们还需要前台显示代码:
function my_get_post_views($before = '阅读(', $after = ')') { global $post; $post_ID = $post->ID; $views = (int) get_post_meta($post_ID, 'views', true); if( _hui('views_w_on') ){ if( $views>=100000 ){ $views = '10W+'; }elseif( $views>=10000 ){ $views = '1W+'; } } return $before . $views . $after; }
我们还需要将这些代码在想要的页面调用,
// 页面头部代码 function my_the_head() { if (is_singular()) { cwtk_add_cookie(get_the_ID()); } _post_views_record(); } add_action('wp_head', '_the_head');
最后在需要前台需要显示的地方添加如下代码:
<!?php echo _get_post_views() ?>