【问题标题】:How to remove one specific category (uncategorized) from post permalinks如何从帖子永久链接中删除一个特定类别(未分类)
【发布时间】:2026-02-11 00:05:02
【问题描述】:

我的 wordpress 网站上有几篇文章。 它们中的大多数属于特定类别,但有些不属于。

对于属于某个类别的所有帖子,我希望具有以下永久链接结构: /%category%/%postname%/

所有其他默认帖子“自动”属于未分类类别。 他们的 URL 结构看起来像这样 /uncategorized/%postname%/

我想将永久链接更改为以下内容:/%postname%/

有没有办法对属于未分类类别的永久链接进行例外处理?

提前致谢!

【问题讨论】:

  • 您是否从管理员那里检查了永久链接选项。
  • 我有。但是只能为所有帖子定义一个永久链接结构。我在那里定义了 /%category%/%postname%/ 。但我希望所有属于未分类类别的帖子都有不同的永久链接结构。你有什么想法来实现这个吗?
  • 有一个固定链接插件,你可以试试那个链接:wordpress.org/support/plugin/advanced-permalinks,但是很久没有更新了。你可以试试看是否适合你
  • 感谢您的建议,但根据开发人员的评论,该插件存在错误。我希望有另一种解决方案

标签: wordpress permalinks


【解决方案1】:

The solution bellow 为我工作。

在function.php中,添加:

if the post is category "uncategorized" or child of "uncategorized" as the main category, change the permalink rule of "/%category%/%postname%" to "/%postname%"

function my_pre_post_link( $permalink, $post, $leavename ) {
  if( $post->post_type != 'post' ) return $permalink;
  $cats = get_the_category($post->ID);
  if( ! count($cats) ) return $permalink;

  usort($cats, '_usort_terms_by_ID');
  $category_object = apply_filters( 'post_link_category', $cats[0], $cats, $post );

  $category_object = get_term( $category_object, 'category' );

  return _clear_uncategorized($category_object, $permalink);
}

function _clear_uncategorized($cat, $permalink) {
  if( $cat->slug == 'uncategorized' ) {
    return str_replace('%category%/', '', $permalink);
  }
  $parent = $cat->parent;
  if ( !$parent )
    return $permalink;
  return _clear_uncategorized($parent, $permalink);
}

add_filter( 'pre_post_link', 'my_pre_post_link', 9, 3 );

【讨论】:

  • 这对我不起作用,当我尝试访问该站点的链接时,该链接始终显示 404 页面。我认为问题出在 htaccess 上,但我无法解决此问题。