如何将WordPress自定义分类法归档链接设置为/%category%/%taxonomy%
解决WordPress自定义分类法归档URL与模板匹配问题
1. 修正自定义分类法注册代码
调整register_taxonomy的参数,确保分类法配置适配后续重写规则:
register_taxonomy( 'season', 'post', array( 'public' => true, 'hierarchical' => true, 'labels' => array( 'name' => '季', ), 'rewrite' => array( 'slug' => 'season', 'with_front' => false, 'hierarchical' => true, ), 'query_var' => 'season', ) );
2. 添加自定义重写规则
让WordPress优先识别/%category%/%season%格式的URL,并映射到season分类法查询:
function custom_season_rewrite_rules() { add_rewrite_rule( '^([^/]+)/([^/]+)/?$', 'index.php?category_name=$matches[1]&season=$matches[2]', 'top' ); } add_action('init', 'custom_season_rewrite_rules');
3. 自动生成目标格式的归档链接
过滤term_link,让season分类的归档链接自动生成为/%category%/%season%结构:
function custom_season_term_link($termlink, $term, $taxonomy) { if ($taxonomy === 'season') { // 获取该季关联的第一篇文章,提取所属分类(若一个季对应多个分类,需调整逻辑) $posts = get_posts(array( 'numberposts' => 1, 'post_type' => 'post', 'tax_query' => array( array( 'taxonomy' => 'season', 'field' => 'term_id', 'terms' => $term->term_id, ) ) )); if (!empty($posts)) { $category = get_the_category($posts[0]->ID); if (!empty($category)) { $cat_slug = $category[0]->slug; $termlink = home_url('/' . $cat_slug . '/' . $term->slug . '/'); } } } return $termlink; } add_filter('term_link', 'custom_season_term_link', 10, 3);
4. 强制加载指定模板
避免WordPress优先匹配分类规则而加载category.php,强制在season查询时使用taxonomy-season.php:
function custom_season_template($template) { if (is_tax('season') || (isset($_GET['season']) && !empty($_GET['season']))) { $new_template = locate_template(array('taxonomy-season.php')); if (!empty($new_template)) { return $new_template; } } return $template; } add_filter('template_include', 'custom_season_template');
关键操作
修改代码后,务必进入WordPress后台「设置-固定链接」页面,点击「保存更改」刷新重写规则,否则新规则不会生效。
内容的提问来源于stack exchange,提问作者Chris Wickham
相关产品推荐
相关产品推荐

