求助: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; }
修改说明
- 钩子替换:用
wp钩子替代template_redirect,触发时机更合理,确保产品页面的条件判断准确 - 范围限制:添加
!is_admin()、!wp_doing_cron()、!is_robot()排除无效访问场景 - 性能优化:直接使用
get_post_meta和update_post_meta操作元数据,避免加载完整产品对象 - 边界处理:自动初始化不存在的计数元数据为0
- 可选去重:通过session实现用户级去重,提升统计准确性
内容的提问来源于stack exchange,提问作者Andrey Miller
相关产品推荐
相关产品推荐

