WooCommerce父子分类URL异常:错误父分类路径未返回404状态码
修复WooCommerce子分类错误父URL返回200的问题
问题根源
WordPress的分类重写规则会忽略URL中父分类的错误片段,直接匹配到对应的子分类,导致即便父分类部分输入错误,页面仍正常加载并返回200状态码,这会引发重复内容的SEO风险。你原有的钩子仅检查子分类是否存在,未验证URL中的父分类是否与子分类实际层级匹配,因此无法触发404。
正确实现代码
替换你原有的代码,使用以下函数验证URL中的父分类路径是否与子分类实际层级一致:
add_action('template_redirect', 'wc_validate_category_parent_path'); function wc_validate_category_parent_path() { // 仅在产品分类页面执行逻辑 if (!is_product_category()) { return; } $category = get_queried_object(); if (!$category || $category->taxonomy !== 'product_cat') { return; } // 解析当前请求路径,剥离分类基础前缀 $request_path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'); $category_base = get_option('woocommerce_permalinks')['category_base'] ?? 'product-category'; $category_path = str_replace($category_base . '/', '', $request_path); // 分割URL中的分类slug层级 $url_slugs = explode('/', $category_path); // 单级分类场景直接跳过验证 if (count($url_slugs) <= 1) { return; } // 获取当前分类的实际完整层级slug(从顶级父类到当前子类) $actual_slugs = []; $current_term = $category; while ($current_term) { array_unshift($actual_slugs, $current_term->slug); $current_term = get_term($current_term->parent, 'product_cat'); } // 对比URL层级与实际层级,不一致则触发404 if ($url_slugs !== $actual_slugs) { global $wp_query; $wp_query->set_404(); status_header(404); nocache_headers(); include(get_query_template('404')); exit; } }
代码说明
- 先提取当前请求的分类路径,剥离掉
product-category前缀,得到URL中的分类slug序列。 - 递归获取子分类的所有父分类slug,构建实际的层级序列。
- 对比两个序列,若不一致则判定URL无效,触发404状态码。
- 兼容单级分类场景,避免误拦截正常请求。
使用方式
将上述代码添加到主题的functions.php文件,或通过自定义插件引入。测试时修改子分类URL中的父分类部分,页面应返回404错误。
内容的提问来源于stack exchange,提问作者Alipvd
相关产品推荐
相关产品推荐

