有一些 Wordpress 插件提供文章阅读次数统计的功能,今天分享一段代码同样可以实现文章阅读次数统计。这样就可以不用安装相关插件了。

把下面代码添加到主题的 functions 文件中

//get post views
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);

}

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');

然后把以下调用阅读次数的代码添加到你需要的地方即可。

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