You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Elementor插件功能展示文章真实浏览量

解决WordPress文章浏览量重复计数问题

你的代码目前每次刷新页面都会触发计数增加,核心问题是没有判断访客是否属于重复浏览。可以通过Cookie记录访客已浏览的文章ID,并排除搜索引擎爬虫,实现真实浏览量统计,修改后的代码如下:

/* Counter PostViews*/
function set_post_view_custom_field() {
    // 仅在单篇文章页面执行,排除预览状态
    if ( is_single() && !is_preview() ) {
        global $post;
        $post_id = $post->ID;
        $cookie_name = 'viewed_posts';
        $expire_time = 24 * 60 * 60; // 24小时内重复访问不计数

        // 排除搜索引擎爬虫
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $crawlers = array('bot', 'crawl', 'spider', 'slurp', 'curl');
        $is_crawler = false;
        foreach ($crawlers as $crawler) {
            if (stripos($user_agent, $crawler) !== false) {
                $is_crawler = true;
                break;
            }
        }
        if ($is_crawler) return;

        // 获取已浏览文章的Cookie记录
        $viewed_posts = isset($_COOKIE[$cookie_name]) ? explode(',', $_COOKIE[$cookie_name]) : array();

        // 当前文章未被浏览过,才更新计数
        if (!in_array($post_id, $viewed_posts)) {
            $post_view_count = get_post_meta($post_id, 'post_view_count', true);
            $count = $post_view_count ? intval($post_view_count) + 1 : 1;
            update_post_meta($post_id, 'post_view_count', $count);

            // 更新Cookie,记录当前文章ID
            $viewed_posts[] = $post_id;
            setcookie($cookie_name, implode(',', $viewed_posts), time() + $expire_time, COOKIEPATH, COOKIE_DOMAIN);
        }
    }
}
// 替换原钩子,template_redirect比wp_head执行时机更合理,避免提前触发
add_action('template_redirect', 'set_post_view_custom_field');

关键修改说明:

  • Cookie防重复:用Cookie存储用户已浏览的文章ID,24小时内重复访问同一文章不会重复计数
  • 爬虫过滤:通过User-Agent识别常见爬虫,避免爬虫刷新导致的计数虚高
  • 钩子优化:将wp_head换成template_redirect,确保在页面渲染前完成计数逻辑,减少无效触发
  • 类型安全:用intval()确保计数值为整数,避免非数值数据引发的错误

内容的提问来源于stack exchange,提问作者user19430201

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 08:40:49