WordPress主題開發:設置和獲取瀏覽次數


將以下代碼放在functions.php,一個是獲取閱讀量,一個是設置閱讀量

<?php

/**
* getPostViews()函數
* 功能:獲取閱讀數量
* 在需要顯示瀏覽次數的位置,調用此函數
* @Param object|int $postID   文章的id
* @Return string $count          文章閱讀數量
*/
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;
 }


/**
* setPostViews()函數  
* 功能:設置或更新閱讀數量
* 在內容頁(single.php,或page.php )調用此函數
* @Param object|int $postID   文章的id
* @Return string $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 );
     }
 }

?>

 注意:調用了setPostViews函數后,每刷新一次就會增加一次瀏覽量。

在內容頁(single.php,或page.php )嘗試一下吧:

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

 

參考文檔:

http://wp-snippets.com/post-views-without-plugin/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM