如何在WordPress中移除URL里的product-category分类别名?
移除WordPress产品分类URL中的"product-category"前缀(无需插件)
如果你试过后台「设置」→「固定链接」里的移除前缀选项无效,可以通过以下自定义代码实现,无需依赖插件:
步骤1:确认固定链接结构
先进入「设置」→「固定链接」,将固定链接设置为自定义结构,填入 /%postname%/,点击「保存更改」。这一步是确保基础重写规则正常运行。
步骤2:添加自定义代码到主题functions.php
登录后台后,进入「外观」→「主题文件编辑器」,找到当前激活主题的functions.php文件,将以下代码添加到文件末尾:
// 移除产品分类的URL前缀 function remove_product_category_base() { global $wp_rewrite; $wp_rewrite->extra_permastructs['product_category']['struct'] = '%product_category%'; } add_action('init', 'remove_product_category_base'); // 重写规则并修复分类查询逻辑 function fix_product_category_rewrite_rules($rules) { $new_rules = array(); // 获取所有产品分类 $terms = get_terms(array( 'taxonomy' => 'product_category', 'hide_empty' => false, )); // 为每个分类生成对应的重写规则 foreach ($terms as $term) { $term_slug = $term->slug; // 分类首页规则 $new_rules[$term_slug . '/?$'] = 'index.php?product_category=' . $term_slug; // 分类分页规则 $new_rules[$term_slug . '/page/([0-9]+)/?$'] = 'index.php?product_category=' . $term_slug . '&paged=$matches[1]'; } // 将新规则放在现有规则前,确保优先匹配 return $new_rules + $rules; } add_filter('rewrite_rules_array', 'fix_product_category_rewrite_rules'); // 修复分类归档页面的链接生成 function fix_product_category_link($link, $term) { if ($term->taxonomy === 'product_category') { return str_replace('/product-category/', '/', $link); } return $link; } add_filter('term_link', 'fix_product_category_link', 10, 2);
步骤3:刷新重写规则
添加代码并保存后,再次进入「设置」→「固定链接」,无需修改任何设置,直接点击「保存更改」,这会刷新WordPress的重写规则,让新的URL结构生效。
注意事项
- 操作前请备份
functions.php文件,避免代码错误导致网站无法访问; - 之后新增产品分类时,需要再次进入固定链接页面点击「保存更改」,刷新规则才能让新分类的URL生效;
- 如果服务器端有自定义的
.htaccess规则,需确保和WordPress的重写规则没有冲突。
内容的提问来源于stack exchange,提问作者Kaffo
相关产品推荐
相关产品推荐

