需求
文章浏览量是内容运营的核心指标。本文实现轻量级浏览量统计,并在首页/侧栏输出热门排行。
一、浏览量计数
Text
add_action('wp_head', function () {
if (is_single()) {
$id = get_the_ID();
$n = (int) get_post_meta($id, 'ji_views', true);
update_post_meta($id, 'ji_views', $n + 1);
}
});
二、热门排行查询
Text
function ji_hot_posts($limit = 8) {
$q = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => $limit,
'meta_key' => 'ji_views',
'orderby' => 'meta_value_num',
'order' => 'DESC',
));
return $q;
}
三、前端展示
Text
<ol class="ji-hot-list">
<?php $hot = ji_hot_posts(); while ($hot->have_posts()) { $hot->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php } wp_reset_postdata(); ?>
</ol>
注意事项
- 高并发站点建议用 Redis 计数异步落库,避免写放大。
- 浏览量统计排除爬虫 UA 更准确。

