透過 wp 程式自己做網站時,如果想在網站上顯示每片文章的瀏覽量,一般都會使用 WordPress 瀏覽量外掛 WP-PostViews, 它可以方便的統計我們網站的每篇文章的瀏覽量。
WordPress 外掛的好處在於使用方便簡單,缺點在於會拖累我們網站開啟速度。下面就來分享 WordPress 無外掛純程式碼方法呼叫網站瀏覽量的方法,供新手學做網站學員使用。
首先在網站後臺的模板函式檔案中加入以下的程式碼:
//獲取瀏覽數-引數文章 ID
function getPostViews($postID){
//欄位名稱
$count_key = 'post_views_count';
//獲取欄位值即瀏覽次數
$count = get_post_meta($postID, $count_key, true);
//如果為空設定為 0
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0";
}
return $count;
}
//設定瀏覽數-引數文章 ID
function setPostViews($postID) {
//欄位名稱
$count_key = 'post_views_count';
//先獲取獲取欄位值即瀏覽次數
$count = get_post_meta($postID, $count_key, true);
//如果為空就設為 0
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
//如果不為空,加 1,更新資料
++$count;
update_post_meta($postID, $count_key, $count);
}
}
在需要顯示瀏覽量的地方,新增瀏覽量呼叫程式碼:<?php echo getPostViews(get_the_ID()); ?>
這樣就可以透過無外掛的方式去實現網站瀏覽量資料了。