B2主题文章浏览量统计与热门排行模块

需求

文章浏览量是内容运营的核心指标。本文实现轻量级浏览量统计,并在首页/侧栏输出热门排行。

一、浏览量计数

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 更准确。

给TA打赏
共{{data.count}}人
人已打赏
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
签到成功