如何修正WooCommerce产品固定链接中brand slug后的多余斜杠?
解决WooCommerce产品固定链接添加Brand Slug并移除多余斜杠的问题
你遇到的这个斜杠问题,核心原因是固定链接设置里的/product/%brand%-写法触发了WordPress的默认分隔规则——它会自动为每个占位符添加斜杠,最终导致出现brand-/product-name这种多余斜杠的情况。咱们换个思路,通过代码直接控制链接的拼接逻辑,具体方案如下:
步骤1:调整固定链接基础设置
先把固定链接设置里的自定义基础改回/product/,去掉%brand%-这部分,后续的slug拼接完全交给代码处理。
步骤2:替换post_type_link过滤器代码
把你原来的代码替换成下面这段,它会直接将brand的slug与产品名称拼接在一起,从根源避免多余斜杠:
add_filter('post_type_link', 'productbrand_permalink_structure', 10, 4); function productbrand_permalink_structure($post_link, $post, $leavename, $sample) { // 仅处理WooCommerce产品类型 if ($post->post_type !== 'product') { return $post_link; } // 获取产品关联的brand分类术语 $brand_terms = get_the_terms($post->ID, 'brand'); if (!empty($brand_terms) && !is_wp_error($brand_terms)) { // 取第一个brand分类的slug(若产品多分类,可将array_pop改为array_shift取第一个) $brand_slug = array_pop($brand_terms)->slug; // 替换原链接中的产品名称部分,拼接brand slug与产品名 if (!$leavename) { $post_link = str_replace('/' . $post->post_name . '/', '/' . $brand_slug . '-' . $post->post_name . '/', $post_link); } else { // 处理预览或名称留空的场景 $post_link = rtrim($post_link, '/') . '-' . $brand_slug . '/'; } } else { // 无brand分类时使用默认值,可自行修改默认文本 $default_slug = 'uncategorized'; if (!$leavename) { $post_link = str_replace('/' . $post->post_name . '/', '/' . $default_slug . '-' . $post->post_name . '/', $post_link); } else { $post_link = rtrim($post_link, '/') . '-' . $default_slug . '/'; } } return $post_link; }
步骤3:刷新WordPress重写规则
代码添加完成后,一定要进入设置→固定链接页面,无需修改任何内容,直接点击「保存更改」按钮刷新重写规则,新的链接结构才会生效。
额外提示
- 如果你的产品可能关联多个brand分类,可根据需求调整
array_pop为array_shift(取第一个分类),或自定义逻辑选择特定分类。 - 确保你的
brand是正确注册的自定义分类法,且已与WooCommerce产品类型关联。
内容的提问来源于stack exchange,提问作者Cray
相关产品推荐
相关产品推荐

