如何为URL添加带父子关系的层级自定义分类法?(以location分类为例)
实现自定义分类法Location的层级URL结构
嘿,针对你需要的层级URL结构(比如domain.com/India/、domain.com/India/Delhi/),咱们可以通过调整WordPress自定义分类法的注册规则和重写设置来实现,一步步来:
1. 先确保自定义分类法location的注册配置正确
在你的主题functions.php或者自定义插件里,注册location分类法时,必须开启层级支持并配置好重写参数,这样WordPress才能识别父子分类的URL结构:
function register_location_taxonomy() { $args = array( 'hierarchical' => true, // 关键:开启父子分类的层级支持 'labels' => array( 'name' => _x( 'Locations', 'taxonomy general name' ), 'singular_name' => _x( 'Location', 'taxonomy singular name' ), // 其他标签比如编辑、添加新项等可以按需补充 ), 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => '', // 留空让分类名直接作为URL的顶级分段 'with_front' => false, // 去掉WordPress默认的前缀(比如/blog/这类) 'hierarchical' => true, // 允许生成层级化的URL路径 ), ); // 这里假设分类法关联的文章类型是post,如果你是自定义文章类型,替换成对应的slug即可 register_taxonomy( 'location', 'post', $args ); } add_action( 'init', 'register_location_taxonomy' );
2. 刷新固定链接规则
代码添加完成后,一定要去WordPress后台的设置→固定链接页面,不用修改任何选项,直接点击「保存更改」按钮。这一步会强制WordPress刷新重写规则,让新的分类URL结构生效。
3. (可选)让文章URL也包含层级Location路径
如果希望关联城市的文章URL也变成domain.com/India/Delhi/post-name/这种结构,可以用过滤器来修改文章的永久链接:
function custom_location_post_permalink( $permalink, $post ) { // 只处理目标文章类型,这里以默认的post为例 if ( $post->post_type !== 'post' ) { return $permalink; } // 获取文章关联的location分类,取层级最深的那个(也就是城市分类) $locations = wp_get_post_terms( $post->ID, 'location', array( 'orderby' => 'parent', 'order' => 'DESC' ) ); if ( ! empty( $locations ) ) { $current_term = $locations[0]; $location_path = ''; // 递归拼接父分类到子分类的完整路径 while ( $current_term ) { $location_path = '/' . $current_term->slug . $location_path; $parent_term = get_term( $current_term->parent, 'location' ); $current_term = is_wp_error( $parent_term ) ? false : $parent_term; } // 替换原链接,生成带层级路径的文章URL $permalink = home_url( trailingslashit( $location_path . '/' . $post->post_name ) ); } return $permalink; } add_filter( 'post_type_link', 'custom_location_post_permalink', 10, 2 );
4. 测试验证
完成上面的步骤后,你就能得到想要的URL结构了:
- 印度分类归档页:
domain.com/India/ - 德里分类归档页:
domain.com/India/Delhi/ - 关联德里的文章:
domain.com/India/Delhi/your-post-title/
小提醒
- 如果遇到URL访问404的情况,先检查固定链接是否刷新,也可以临时在代码里加一次
flush_rewrite_rules();(注意:不要一直放在init钩子中,只在修改配置后运行一次即可)。 - 建议给分类项设置英文slug(比如India、Delhi),避免中文slug带来的编码或兼容性问题。
内容的提问来源于stack exchange,提问作者Saurin Dashadia
相关产品推荐
相关产品推荐

