wordpress本身不带文章浏览统计,可以用插件wp-postview,但是刷新还是算一个浏览次数。
1.首先在主题下functions.php里增加以下代码,这段代码也是网上可以找到的
1 //add by charleswu 2 function getPostViews($postID) { 3 $count_key = 'post_views_count'; 4 $count = get_post_meta($postID, $count_key, true); 5 if ($count == '') { 6 delete_post_meta($postID, $count_key); 7 add_post_meta($postID, $count_key, '0'); 8 return "0"; 9 } 10 return $count; 11 } 12 function setPostViews($postID) { 13 $count_key = 'post_views_count'; 14 $count = get_post_meta($postID, $count_key, true); 15 if ($count == '') { 16 $count = 0; 17 delete_post_meta($postID, $count_key); 18 add_post_meta($postID, $count_key, '0'); 19 } else { 20 $count++; 21 update_post_meta($postID, $count_key, $count); 22 } 23 }
2.解决刷新统计数增加,一定要放在文章页面的最前面,貌似php设置cookie之前不能有输出,蛋疼。我的是single.php页面
1 <?php 2 $post_id=get_the_ID(); 3 if(isset($_COOKIE['views'.$post_id.COOKIEHASH]) && $_COOKIE['views'.$post_id.COOKIEHASH] == '1') 4 { 5 6 } 7 else{ 8 setPostViews($post_id); 9 setcookie('views'.$post_id.COOKIEHASH,'1',time() + 3600,COOKIEPATH,COOKIE_DOMAIN);//设置时间间隔 10 } 11 ?>