WordPress自定义文章类型固定链接问题:重复别名与自定义分类冲突
解决WordPress自定义文章类型同名子页面跳转错误问题
问题根源
- 现有重写规则仅覆盖父级社区页面的URL结构,未处理
/about这类子页面的层级路由 - 查询逻辑仅传递文章名称参数
name,WordPress无法区分不同社区下的同名子页面,默认返回最早发布的匹配文章
解决方案
1. 更新重写规则,支持子页面URL
修改重写规则函数,新增子页面匹配规则,同时传递州、城市、父页面名称等关键参数:
function generated_rewrite_rules() { // 匹配父级社区页面:community/state/city/community-name/ add_rewrite_rule( '^community/([^/]+)/([^/]+)/([^/]+)/?$', 'index.php?post_type=community&name=$matches[3]&location_state=$matches[1]&location_city=$matches[2]', 'top' ); // 匹配子页面:community/state/city/community-name/child-page/ add_rewrite_rule( '^community/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$', 'index.php?post_type=community&name=$matches[4]&post_parent_name=$matches[3]&location_state=$matches[1]&location_city=$matches[2]', 'top' ); } add_action( 'init', 'generated_rewrite_rules' );
2. 修正固定链接生成逻辑
更新链接生成函数,处理子页面的URL拼接,子页面自动继承父页面的location分类信息:
function change_permalinks( $post_link, $post ){ if ( $post->post_type !== 'community' ) { return $post_link; } // 优先取当前页面的location分类,无分类则继承父页面的 $terms = wp_get_object_terms( $post->ID, 'location' ); if ( empty( $terms ) && $post->post_parent ) { $terms = wp_get_object_terms( $post->post_parent, 'location' ); } if ( ! empty( $terms ) ) { // 按分类层级排序(州为父分类,城市为子分类) usort( $terms, function( $a, $b ) { return $a->parent - $b->parent; } ); $state_slug = $terms[0]->slug; $city_slug = $terms[1]->slug; // 子页面拼接父页面slug if ( $post->post_parent ) { $parent_post = get_post( $post->post_parent ); $parent_slug = $parent_post->post_name; return str_replace( '%comm%', "{$state_slug}/{$city_slug}/{$parent_slug}", $post_link ); } else { return str_replace( '%comm%', "{$state_slug}/{$city_slug}", $post_link ); } } return $post_link; } add_filter( 'post_type_link', 'change_permalinks', 10, 2 );
3. 精准化查询逻辑
添加查询过滤器,让WordPress结合父页面ID和location分类筛选页面,避免同名冲突:
function filter_community_query( $query ) { if ( ! is_admin() && $query->is_main_query() && $query->get( 'post_type' ) === 'community' ) { $state_slug = $query->get( 'location_state' ); $city_slug = $query->get( 'location_city' ); $parent_name = $query->get( 'post_parent_name' ); // 通过父页面名称获取对应ID,筛选子页面 if ( $parent_name ) { $parent_post = get_page_by_path( $parent_name, OBJECT, 'community' ); if ( $parent_post ) { $query->set( 'post_parent', $parent_post->ID ); } } // 通过location分类的城市slug筛选页面 if ( $state_slug && $city_slug ) { $query->set( 'tax_query', array( array( 'taxonomy' => 'location', 'field' => 'slug', 'terms' => $city_slug, 'include_children' => false ) ) ); } } } add_action( 'pre_get_posts', 'filter_community_query' );
4. 刷新重写规则缓存
进入WordPress后台「设置」→「固定链接」页面,直接点击保存更改,无需修改任何设置,触发重写规则更新。
内容的提问来源于stack exchange,提问作者kfww-dev
相关产品推荐
相关产品推荐

