如何重写WordPress中关联WP_User的自定义分类法友好URL结构
实现方案
这种URL结构是完全可以实现的,核心需要修改分类法注册参数、添加自定义重写规则、适配查询逻辑、自定义链接生成四个步骤,具体操作如下:
1. 调整分类法注册参数
首先需要禁用分类法默认的重写规则,避免默认生成的分类法前缀URL和自定义规则冲突,注册代码调整为:
$common_args = [ // 你原有分类法的其他参数,比如label、hierarchical等保持不变 'rewrite' => false, // 禁用默认重写 'query_var' => true, // 保留查询变量,后续重写规则需要用到 ]; register_taxonomy('type', 'user', $common_args); register_taxonomy('city', 'user', $common_args);
2. 添加自定义重写规则
在主题functions.php或自定义插件中添加以下重写规则,注意规则需要按优先级从高到低排列:
add_action('init', 'custom_user_tax_rewrite_rules'); function custom_user_tax_rewrite_rules() { // 匹配 /type/city/user/ 结构的用户详情页 add_rewrite_rule( '^([^/]+)/([^/]+)/([^/]+)/?$', 'index.php?author_name=$matches[3]&type=$matches[1]&city=$matches[2]', 'top' ); // 匹配 /type/city/ 结构的双分类用户归档页 add_rewrite_rule( '^([^/]+)/([^/]+)/?$', 'index.php?type=$matches[1]&city=$matches[2]', 'top' ); // 匹配 /type/ 结构的单分类用户归档页 add_rewrite_rule( '^([^/]+)/?$', 'index.php?type=$matches[1]', 'top' ); }
规则添加后,进入WordPress后台「设置」-「固定链接」,点击保存按钮刷新重写规则,配置即可生效。
3. 适配查询逻辑
因为默认WordPress的分类法查询默认针对文章类型,你关联的是用户对象,需要添加钩子适配查询:
add_action('template_redirect', 'custom_user_tax_template_redirect'); function custom_user_tax_template_redirect() { $type = get_query_var('type'); $city = get_query_var('city'); $author_name = get_query_var('author_name'); // 用户详情页逻辑 if ($author_name && $type && $city) { $user = get_user_by('slug', $author_name); if ($user) { // 校验用户是否属于对应的type和city分类,避免非法URL访问 if (has_term($type, 'type', $user->ID) && has_term($city, 'city', $user->ID)) { // 加载自定义用户资料模板,模板放在主题根目录即可 include(get_template_directory() . '/user-profile.php'); exit; } } } // 分类归档页逻辑 if ($type || $city) { // 加载自定义用户归档模板 include(get_template_directory() . '/user-archive.php'); exit; } }
你需要自行在主题目录新建user-archive.php和user-profile.php两个模板文件,分别写用户列表和用户详情的展示逻辑即可。
4. 自定义链接生成
为了让站点内输出的分类链接、用户链接自动符合你的URL结构,需要添加两个过滤器:
// 自定义分类链接 add_filter('term_link', 'custom_user_tax_term_link', 10, 3); function custom_user_tax_term_link($termlink, $term, $taxonomy) { if ($taxonomy == 'type') { return home_url('/' . $term->slug . '/'); } if ($taxonomy == 'city') { // 获取当前上下文的type分类,拼接双分类链接 $type_slug = get_query_var('type'); if ($type_slug) { return home_url('/' . $type_slug . '/' . $term->slug . '/'); } } return $termlink; } // 自定义用户个人主页链接 add_filter('author_link', 'custom_user_profile_link', 10, 2); function custom_user_profile_link($link, $author_id) { // 获取用户对应的type和city分类slug $type_terms = wp_get_object_terms($author_id, 'type', ['fields' => 'slugs']); $city_terms = wp_get_object_terms($author_id, 'city', ['fields' => 'slugs']); if (!empty($type_terms) && !empty($city_terms)) { $user = get_user_by('id', $author_id); return home_url('/' . $type_terms[0] . '/' . $city_terms[0] . '/' . $user->user_nicename . '/'); } return $link; }
注意事项
- 需要保证
type分类的slug不会和你站点已有的页面、文章、自定义文章类型的slug重复,否则会出现URL优先级冲突 - 如果一个用户关联了多个
type或city分类,上面示例默认取第一个分类生成链接,你可以根据自己的需求调整逻辑
内容的提问来源于stack exchange,提问作者fgs
相关产品推荐
相关产品推荐

