如何实现双custom taxonomies组合的食谱归档URL?能否用Custom Post Type UI配置?
实现自定义分类组合归档的解决方案
首先明确:Custom Post Type UI(CPT UI)无法直接配置多分类组合的归档路由和查询逻辑,它的核心作用是创建自定义文章类型(CPT)和关联的自定义分类法,多分类组合归档需要通过代码实现,以下是具体步骤:
1. 添加自定义重写规则
在主题的functions.php文件(或自定义插件)中添加代码,解析/recipes/tagged/lunch+chicken这类URL并映射到正确的查询参数:
精准匹配两个分类术语的版本
function recipes_add_combined_taxonomy_rewrite() { add_rewrite_rule( '^recipes/tagged/([^+]+)\+([^/]+)/?', 'index.php?post_type=recipes&meal=$matches[1]&ingredient=$matches[2]', 'top' ); } add_action('init', 'recipes_add_combined_taxonomy_rewrite');
添加代码后,进入WordPress后台设置→固定链接页面,点击「保存更改」刷新重写规则,否则新URL会返回404错误。
2. 调整主查询参数
用pre_get_posts钩子确保查询只返回同时匹配两个分类术语的recipes文章:
function recipes_filter_combined_taxonomy_query($query) { if (!is_admin() && $query->is_main_query() && $query->get('post_type') === 'recipes') { $meal = $query->get('meal'); $ingredient = $query->get('ingredient'); if ($meal && $ingredient) { $tax_query = array( 'relation' => 'AND', array( 'taxonomy' => 'meal', 'field' => 'slug', 'terms' => $meal, ), array( 'taxonomy' => 'ingredient', 'field' => 'slug', 'terms' => $ingredient, ), ); $query->set('tax_query', $tax_query); } } } add_action('pre_get_posts', 'recipes_filter_combined_taxonomy_query');
3. 创建自定义归档模板
复制主题现有的archive-recipes.php文件,重命名为archive-recipes-tagged.php,修改模板内容(比如添加组合分类标题)。也可以用钩子指定模板:
function recipes_set_combined_taxonomy_template($template) { if (is_post_type_archive('recipes') && get_query_var('meal') && get_query_var('ingredient')) { $custom_template = locate_template('archive-recipes-tagged.php'); if ($custom_template) { return $custom_template; } } return $template; } add_filter('template_include', 'recipes_set_combined_taxonomy_template');
4. 生成组合分类链接
在模板中生成类似/recipes/tagged/lunch+chicken的组合链接:
// 假设$meal_term和$ingredient_term是对应的分类术语对象 $combined_url = home_url('/recipes/tagged/' . $meal_term->slug . '+' . $ingredient_term->slug); echo '<a href="' . esc_url($combined_url) . '">' . $meal_term->name . ' & ' . $ingredient_term->name . ' 食谱</a>';
注意事项
- 确保在CPT UI创建
meal和ingredient分类法时,「查询变量」处于启用状态,否则参数无法被WordPress识别。 - 若需支持更多分类组合,可修改重写规则和
tax_query逻辑。
内容的提问来源于stack exchange,提问作者Fried Smurf
相关产品推荐
相关产品推荐

