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

求助:WooCommerce单个产品页面浏览量统计功能实现失败

WooCommerce产品页面浏览量统计修复方案

原代码存在的问题

  • 刷新页面就重复计数,无去重逻辑,数据失真
  • 未排除后台管理员、爬虫访问,导致无效统计
  • template_redirect钩子触发时机过早,可能引发产品对象未完全初始化的问题
  • 未处理元数据首次初始化的边界情况

修复后的基础版代码(无用户去重)

add_action('wp', 'update_product_view_count');
function update_product_view_count() {
    // 仅前台产品页面执行,排除管理员、定时任务、爬虫
    if (class_exists('WooCommerce') && is_product() && !is_admin() && !wp_doing_cron() && !is_robot()) {
        $product_id = get_the_ID();
        $count_key = '_product_view_count';
        
        // 获取当前计数,不存在则初始化为0
        $count = (int) get_post_meta($product_id, $count_key, true);
        $count++;
        
        // 直接更新元数据,无需加载完整产品对象,提升效率
        update_post_meta($product_id, $count_key, $count);
    }
}

// 判断是否为爬虫/机器人的辅助函数
function is_robot() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $bot_patterns = ['bot', 'crawl', 'spider', 'slurp', 'curl', 'wget', 'python', 'scrapy'];
    
    foreach ($bot_patterns as $pattern) {
        if (stripos($user_agent, $pattern) !== false) {
            return true;
        }
    }
    return false;
}

带用户去重的增强版代码(同一用户24小时内仅计数一次)

如果需要更精准的统计,避免同一用户短时间内重复刷新导致的计数虚高,可以添加session去重逻辑:

add_action('wp', 'update_product_view_count');
function update_product_view_count() {
    if (class_exists('WooCommerce') && is_product() && !is_admin() && !wp_doing_cron() && !is_robot()) {
        $product_id = get_the_ID();
        $count_key = '_product_view_count';
        $session_key = 'viewed_product_' . $product_id;
        
        // 检查session,同一用户24小时内浏览同一产品不重复计数
        if (!isset($_SESSION[$session_key]) || $_SESSION[$session_key] < (time() - 86400)) {
            $count = (int) get_post_meta($product_id, $count_key, true);
            $count++;
            update_post_meta($product_id, $count_key, $count);
            
            // 更新session记录当前时间
            $_SESSION[$session_key] = time();
        }
    }
}

// 确保WordPress启动session
add_action('init', function() {
    if (!session_id()) {
        session_start();
    }
});

// 判断是否为爬虫/机器人的辅助函数
function is_robot() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $bot_patterns = ['bot', 'crawl', 'spider', 'slurp', 'curl', 'wget', 'python', 'scrapy'];
    
    foreach ($bot_patterns as $pattern) {
        if (stripos($user_agent, $pattern) !== false) {
            return true;
        }
    }
    return false;
}

修改说明

  1. 钩子替换:用wp钩子替代template_redirect,触发时机更合理,确保产品页面的条件判断准确
  2. 范围限制:添加!is_admin()、!wp_doing_cron()、!is_robot()排除无效访问场景
  3. 性能优化:直接使用get_post_meta和update_post_meta操作元数据,避免加载完整产品对象
  4. 边界处理:自动初始化不存在的计数元数据为0
  5. 可选去重:通过session实现用户级去重,提升统计准确性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 20:43:21