1. 程式人生 > >非外掛純程式碼實現WordPress增加瀏覽次數統計及顯示評論數

非外掛純程式碼實現WordPress增加瀏覽次數統計及顯示評論數

9166166-389fde55e2dde833.jpg 非外掛純程式碼實現WordPress增加瀏覽次數統計及顯示評論數

wp站點有一段時間了,之前優化了首頁載入速度,又感覺缺少瀏覽次數的統計很不方便,於是便折騰了一下,對瀏覽次數和評論數做了下優化

統計瀏覽次數

這個功能做得比較簡單,沒有做使用者及ip去重,只是單純的統計頁面開啟次數,將下面程式碼加入模板的function.php中即可

/**
 * 設定閱讀次數
 * 注意count_key, 後續都是根據這個來統計的
 */
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');  

獲取瀏覽次數

下面函式可以獲取瀏覽次數,在需要顯示的地方呼叫即可

/**
 * 閱讀次數
 * count_key與set函式的count_key一致
 */
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);   
} 

使用示例

最常規的使用應該是文章詳情中,一般是文章頁面 (single.php)的while ( have_posts() )後面,部分single.php中有get_template_part( 'template-parts/content', 'single');則需要到conent加上下面的程式碼

<?php get_post_views($post -> ID); ?> 閱讀

顯示評論次數

在上面瀏覽次數之後,可以加上評論次數顯示

<?php get_post_views($post -> ID); ?> 閱讀
&#160;/&#160;
<?php comments_number('暫無評論', '1條評論', '% 評論' );?>

在後臺文章列表統計中增加瀏覽次數

require_once( trailingslashit( get_template_directory() ) . 'trt-customize-pro/newslite/class-customize.php' );

//在後臺文章列表增加一列資料
add_filter( 'manage_posts_columns', 'ashuwp_customer_posts_columns' );
/**
 * 注意"views"需要與之前統計set方法一致
 */
function ashuwp_customer_posts_columns( $columns ) {
    $columns['views'] = '瀏覽次數';
    return $columns;
}
 
//輸出瀏覽次數
add_action('manage_posts_custom_column', 'ashuwp_customer_columns_value', 10, 2);

/**
 * 注意"views"需要與之前統計set方法一致
 */
function ashuwp_customer_columns_value($column, $post_id){
    if($column=='views'){
        $count = get_post_meta($post_id, 'views', true);
        if(!$count){
            $count = 0;
        }
        echo $count;
    }
    return;
}

原文:簡書ThinkinLiu 部落格: IT老五

以上程式碼能實現瀏覽次數統計,而且免於安裝外掛。唯一的不好之處是更換主題後,需要重新增加程式碼(不過歷史瀏覽統計資料不會丟),在這裡記錄下,以後需要用到的時候不需要再敲程式碼,同時,也希望能幫到有需要的朋友。