WordPress如何组合两个自定义分类法术语生成SEO友好URL
WordPress双自定义分类法组合URL实现方案
1. 自动生成品牌+地区组合URL及重写规则
首先需要添加自定义重写规则,让WordPress可识别/[品牌别名]/[地区别名]/的路径格式,解析为对应分类的筛选查询。以下代码可放入主题functions.php文件或自定义功能插件中:
// 注册自定义重写规则 function custom_brand_location_rewrite_rules() { add_rewrite_rule( '^([^/]+)/([^/]+)/?$', 'index.php?brand=$matches[1]&location=$matches[2]', 'top' ); } add_action('init', 'custom_brand_location_rewrite_rules');
代码添加完成后,进入WordPress后台「设置」-「固定链接」,直接点击「保存修改」刷新重写规则即可生效,无需修改现有固定链接配置。
如果需要在站点其他位置批量输出所有组合URL,可通过遍历两个分类法的术语实现:
// 批量生成所有品牌+地区的组合URL function get_all_brand_location_urls() { $brands = get_terms([ 'taxonomy' => 'brand', 'hide_empty' => true, // 设为false则包含无关联内容的分类 ]); $locations = get_terms([ 'taxonomy' => 'location', 'hide_empty' => true, ]); $urls = []; foreach($brands as $brand) { foreach($locations as $location) { $urls[] = home_url('/' . $brand->slug . '/' . $location->slug . '/'); } } return $urls; }
2. 将组合URL加入站点地图
以WordPress核心自带的站点地图功能为例,可通过钩子批量插入组合URL:
// 向核心站点地图添加品牌地区组合链接 add_action('wp_sitemaps_init', function($wp_sitemaps) { $urls = get_all_brand_location_urls(); $wp_sitemaps->registry->add( 'custom', 'brand-location', function() use ($urls) { $entries = []; foreach($urls as $url) { $entries[] = [ 'loc' => $url, 'lastmod' => gmdate('c'), 'changefreq' => 'weekly', 'priority' => 0.7 ]; } return $entries; } ); });
如果使用Yoast SEO等第三方SEO插件的站点地图功能,替换为对应插件提供的sitemap条目插入钩子即可,逻辑完全一致。
3. 配置自定义模板
通过template_include钩子即可自定义组合URL的加载模板:
// 自定义品牌+地区组合页的模板加载逻辑 function custom_brand_location_template($template) { if (get_query_var('brand') && get_query_var('location')) { // 自定义模板路径,可自行修改文件名 $custom_template = locate_template('archive-brand-location.php'); if ($custom_template) { return $custom_template; } } return $template; } add_filter('template_include', 'custom_brand_location_template');
之后在主题根目录新建archive-brand-location.php文件,按照普通归档页的写法开发模板即可,模板内可通过get_query_var('brand')和get_query_var('location')获取当前的分类别名,调用对应内容输出。
注意:首次添加重写规则后必须刷新固定链接配置,否则会出现404错误;代码修改前建议提前备份站点文件。
内容的提问来源于stack exchange,提问作者Abhishek Sharma
相关产品推荐
相关产品推荐

