How to remove one specific category (uncategorized) from post permalinks

梦想与她 提交于 2019-12-21 23:50:18

问题


I have several posts on my wordpress site. Most of them belong to a specific category, but some don't.

For all the posts that belong to a category I want to have the following permalink structure: /%category%/%postname%/

All the other default posts belong "automatically" to the uncategorized category. Their URL structure will look like this /uncategorized/%postname%/

I want to change permalinks to the following: /%postname%/

Is there a way to make an exception for the permalinks that belong to the uncategorized category?

Thanks in advance!


回答1:


The solution bellow worked for me.

In function.php, just add :

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 );


来源:https://stackoverflow.com/questions/24697914/how-to-remove-one-specific-category-uncategorized-from-post-permalinks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!