這個功能相信大部分博客都會用到,今天介紹的使用插入代碼的方式來實現這一功能,代碼盲或者懶得折騰代碼的童鞋可以使用這個插件:WP-PostViews
首先進入 WP 後台,主題 – 編輯,找到 functions.php 文件,在適當位置插入下面代碼:
/* Postviews start */
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return " 0 ";
}
return $count;
}
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
/* Postviews start end*/
function getPostViews($postID){
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return " 0 ";
}
return $count;
}
function setPostViews($postID) {
$count_key = 'post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
/* Postviews start end*/
然後在 single.php 中的 endwhile; endif; wp_reset_query(); 循環前添加如下代碼:
<?php setPostViews(get_the_ID());?>
最後在你想要顯示文章瀏覽次數統計的地方 (一般在 index.php 、 sidebar.php 或 single.php 文件) 添加如下代碼即可。