给 WordPress 文章添加阅读次数统计

一般 WordPress 实现文章阅读次数,都是用 wp-postviews 插件,其实用代码也可以简单实现:

后台」→「外观」→「编辑」→ 「functions.php」文件,把下面的代码添加进去:

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

然后在你需要显示的地方插入下面的代码,一般需要添加的文件有 index.php、single.php、archive.php

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

相关文章:给 WordPress 文章添加点赞功能

# 更多WordPress技巧,请关注「WordPress专题