WordPress 不要外掛實現瀏覽次數是把下面的程式碼複製到主題的 functions.php 檔案裡,然後按照步驟 1 和步驟 2 的說明進行操作,就可以顯示每篇文章的被瀏覽次數。
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 View”;
}
return $count.’ Views’;
}
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);
}
}
第一步
將以下程式碼插入 single.php 檔案主迴圈內。
<?php
setPostViews(get_the_ID());
?>
第二步
你想在哪個版塊 (比如側欄) 顯示文章的瀏覽次數,就在相應的模板檔案 (側欄對應檔案 sidebar.php) 里加上下面的程式碼:
<?php
echo getPostViews(get_the_ID());
?>
需要注意的是這個方法在安裝了快取外掛的情況下不適用。