我希望这对你有用:D
function mf_post_link( $permalink, $post, $leavename ) {
if( $post->post_type != \'post\' ) return $permalink;
// if no category, the filter is deactivated
$cats = get_the_category($post->ID);
if( ! count($cats) ) return $permalink;
usort($cats, \'_usort_terms_by_ID\'); // order by ID
$category_object = apply_filters( \'post_link_category\', $cats[0], $cats, $post );
$category_object = get_term( $category_object, \'category\' );
$parent = $category_object->parent;
// if no father, the filter is deactivated
if ( !$parent ) return;
$category_parent = get_term( $parent, \'category\' );
// if the parent is not uncategorized, the filter is deactivated
if( $category_parent->slug != \'uncategorized\' ) return $permalink;
return str_replace(\'uncategorized/\', \'\', $permalink);
}
add_filter( \'post_link\', \'mf_post_link\', 9, 3 );
编辑:
如果帖子是“未分类”类别或“未分类”的子类别作为主类别,请将“/%category%/%postname%”的永久链接规则更改为“/%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 );