按国家限制WooCommerce产品可见性时如何排除Google爬虫保障收录
问题根源
你当前使用的代码对所有访问流量统一执行IP属地校验逻辑,Google爬虫抓取页面时如果IP归属美国,会被判定为不可见,无法拿到有效产品内容,因此无法正常收录。
修复后的代码
add_filter( 'woocommerce_product_is_visible', 'bbloomer_hide_product_if_country', 9999, 2 ); function bbloomer_hide_product_if_country( $visible, $product_id ){ // 新增:先判断是否为搜索引擎爬虫,是则直接跳过国家限制 $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? ''; $crawler_identifiers = ['googlebot', 'google-structured-data-testing-tool', 'google-inspectiontool']; foreach ($crawler_identifiers as $crawler) { if (stripos($user_agent, $crawler) !== false) { return $visible; } } // 原有国家限制逻辑保留 $location = WC_Geolocation::geolocate_ip(); $country = $location['country']; if ( $country === "US" ) { $visible = false; } else { $visible = true; } return $visible; }
核心修改说明
- 新增了User-Agent识别逻辑,提前判断访问者是否为Google官方爬虫
- 识别到爬虫访问时直接跳过国家限制校验,返回默认可见状态,保证爬虫可以正常抓取产品内容
- 保留原有普通用户的国家访问限制逻辑,不影响原有业务规则
注意事项
- 如果需要适配其他搜索引擎(如Bing、百度),可以在
$crawler_identifiers数组中新增对应爬虫的UA标识即可 - 修改完成后可以通过Google Search Console的「URL检查」工具验证产品页是否可以被正常抓取索引
- 该实现符合搜索引擎收录规则,不会触发违规判定
内容的提问来源于stack exchange,提问作者Rahapouyan kian
相关产品推荐
相关产品推荐

