這個功能相信大部分部落格都會用到,今天介紹的使用插入程式碼的方式來實現這一功能,程式碼盲或者懶得折騰程式碼的童鞋可以使用這個外掛: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*/

然後在 single.php 中的 endwhile; endif; wp_reset_query(); 迴圈前新增如下程式碼:

<?php setPostViews(get_the_ID());?>

最後在你想要顯示文章瀏覽次數統計的地方 (一般在 index.php 、 sidebar.php 或 single.php 檔案) 新增如下程式碼即可。