# WordPress去除固定链接中的子分类标签

- 原文链接：https://www.xintheme.com/wpjiaocheng/2369.html
- 发布日期：2018-07-17
- 更新时间：2026-08-22
- 作者：大胡子 | XinTheme
- 分类目录：WordPress教程
- 标签：WordPress、WordPress伪静态、WordPress固定链接、WordPress教程

## 摘要

新主题的WordPress固定链接格式是：/%category%/%post_id%.html（分类名/文章ID.html） 但是我有的分类下有很多子分类，那么...

## 正文

新主题的[WordPress](https://www.xintheme.com/)固定链接格式是：/%category%/%post\_id%.html（分类名/文章ID.html）

但是我有的分类下有很多子分类，那么文章链接就会变成：https://www.xintheme.com/父分类/子分类/文章ID.html

这样的话链接目录层次就有点深，从某种方面来讲不太利于SEO优化，然后就要想办法干掉WordPress固定链接中的子分类了，把下面的代码添加到[WordPress主题](https://www.xintheme.com/)中的functions.php里面：

\[php\]// wordpress 去掉固定链接中的子分类https://www.xintheme.com/theme/blog/2294.html  
//去掉后： https://www.xintheme.com/theme/2294.html  
add\_filter('post\_link','custom\_post\_type\_link',10,3);  
function custom\_post\_type\_link($permalink, $post, $leavename) {  
if (!gettype($post) == 'post') {  
return $permalink;}  
switch ($post-&gt;post\_type) {  
case 'post':  
//$permalink = get\_home\_url() . '/' . $post-&gt;post\_name . '/';  
$cats = get\_the\_category($post-&gt;ID);  
$subcats = array();  
foreach( $cats as $cat ) {  
$cat = get\_category($cat-&gt;term\_id);  
//if($cat-&gt;parent) { $subcats\[\] = sanitize\_title($cat-&gt;name);  
if($cat-&gt;parent) { $subcats\[\] = $cat-&gt;slug;}}  
if($subcats) {  
foreach($subcats as $subcat) {  
$subcat = $subcat.'/';  
$permalink = str\_replace($subcat, "", $permalink);}}  
break;}  
return $permalink;} \[/php\]

多级分类解决方法：

\[php\]// wordpress 去掉固定链接中的所有子分类包含孙分类https://www.xintheme.com/theme/blog/ceshi/2294.html  
//去掉后： https://www.xintheme.com/theme/2294.html  
function remove\_child\_categories\_from\_permalinks( $category ) {  
while ( $category-&gt;parent ) {  
$category = get\_term( $category-&gt;parent, 'category' );  
}  
return $category;  
}  
add\_filter( 'post\_link\_category', 'remove\_child\_categories\_from\_permalinks' );\[/php\]