相信不少博客都是用wordpress搭建的,那么我們在不使用插件的情況下如何簡單地實現文章閱讀次數的統計呢?下面有兩個方法可供參考:
方法一:
1、首先打開我們的后台控制面板,點擊外觀——編輯
2、在右欄找到函數模板function.php
在文件的最末尾添加如下代碼
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);
}
}
添加之后記得更新文件
3、然后我們打開文章頁面single.php,找到與下面類似的地方
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
在它的下面添加如下代碼
<?php setPostViews(get_the_ID()); ?>
最后將我們需要展示閱讀次數的地方添加如下代碼
<?php echo getPostViews(get_the_ID()); ?>
方法二:
1、和方法一一樣,找到function.php添加如下代碼:
function get_post_views ($post_id) {
$count_key = 'views';
$count = get_post_meta($post_id, $count_key, true);
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
$count = '0';
}
echo number_format_i18n($count);
}
function set_post_views () {
global $post;
$post_id = $post -> ID;
$count_key = 'views';
$count = get_post_meta($post_id, $count_key, true);
if (is_single() || is_page()) {
if ($count == '') {
delete_post_meta($post_id, $count_key);
add_post_meta($post_id, $count_key, '0');
} else {
update_post_meta($post_id, $count_key, $count + 1);
}
}
}
add_action('get_header', 'set_post_views');
然后在文章頁面single.php的需要顯示的位置添加如下代碼
閱讀次數 <?php get_post_views($post -> ID); ?>
效果:
注意:如果部分博主使用的主題是特殊的主題,那么文章頁面應該是loop-single.php,把上面方法里面的single.php替換成loop-single.php即可