如何在WordPress的URL及文章中同时显示顶级分类与子分类?
WordPress 分类URL与内容显示双分类解决方案
一、让URL同时显示顶级+子分类层级
WordPress默认使用/%category%/%postname%/固定链接时,若同时选中父分类和子分类,会自动忽略父分类只保留子分类路径;仅选子分类时URL正常但内容只显示子分类。要强制URL输出完整的「顶级分类/子分类」结构,可添加以下代码到主题functions.php(或用代码片段插件避免直接修改主题文件):
// 重写分类链接,输出完整层级 function custom_category_permalink($termlink, $term, $taxonomy) { if ($taxonomy !== 'category') return $termlink; $parents = get_ancestors($term->term_id, 'category', 'taxonomy'); array_unshift($parents, $term->term_id); $slug = ''; foreach ($parents as $parent) { $parent_term = get_term($parent, 'category'); $slug .= $parent_term->slug . '/'; } $slug = rtrim($slug, '/'); return home_url(user_trailingslashit($slug)); } add_filter('term_link', 'custom_category_permalink', 10, 3); // 重写文章链接,替换%category%为完整层级 function custom_post_permalink($permalink, $post, $leavename) { if (strpos($permalink, '%category%') === false) return $permalink; $categories = get_the_category($post->ID); if (!$categories) return str_replace('%category%', '', $permalink); $category = end($categories); $parents = get_ancestors($category->term_id, 'category', 'taxonomy'); array_unshift($parents, $category->term_id); $category_slugs = array(); foreach ($parents as $parent) { $term = get_term($parent, 'category'); $category_slugs[] = $term->slug; } $category_str = implode('/', $category_slugs); return str_replace('%category%', $category_str, $permalink); } add_filter('post_link', 'custom_post_permalink', 10, 3);
添加后进入后台「设置→固定链接」,直接点击「保存更改」刷新规则,避免出现404错误。
二、让文章内容同时显示顶级+子分类
默认the_category()函数只会显示最具体的分类,要显示所有选中分类或完整层级,可修改主题中显示分类的代码:
方式1:显示所有选中的分类(含顶级+子分类)
找到主题single.php或content-single.php中调用the_category()的位置,替换为:
$categories = get_the_category(); if ($categories) { echo '<div class="post-categories">'; foreach ($categories as $category) { echo '<a href="' . get_category_link($category->term_id) . '">' . $category->name . '</a>'; if ($category !== end($categories)) echo ', '; } echo '</div>'; }
方式2:显示分类层级(如「顶级分类 > 子分类」)
如果需要展示分类的层级关系而非多个分类,可替换为:
$categories = get_the_category(); if ($categories) { $category = end($categories); $parents = get_ancestors($category->term_id, 'category', 'taxonomy'); array_unshift($parents, $category->term_id); $category_links = array(); foreach ($parents as $parent) { $term = get_term($parent, 'category'); $category_links[] = '<a href="' . get_category_link($term->term_id) . '">' . $term->name . '</a>'; } echo '<div class="category-hierarchy">' . implode(' > ', $category_links) . '</div>'; }
三、操作注意事项
- 发布文章时仅需选择子分类即可,WordPress默认会将子分类文章自动归类到父分类,无需手动勾选父分类;
- 修改主题文件前务必备份,推荐使用「Code Snippets」等代码片段插件管理自定义代码,避免主题更新丢失修改。
内容的提问来源于stack exchange,提问作者Pascal Pugatsch
相关产品推荐
相关产品推荐

