wordpres删除URL中的父级分类或者子分类

当固定链接为.com/一级分类/子分类/文章.html的时候。

1,移除链接中父级分类,比如:.com/二级分类/文章.html

代码如下:

//移除固定链接url中 父级分类
add_filter( 'post_link', 'custom_remove_parent_cats_from_link', 10, 3 );
    function custom_remove_parent_cats_from_link( $permalink, $post, $leavename ){
        $cats = get_the_category( $post->ID );
        if ( $cats ) {
            usort( $cats, '_usort_terms_by_ID' );
            $category = $cats[0]->slug;
        if ( $parent = $cats[0]->parent ) {
            $parentcats = get_category_parents( $parent, false, '/', true );
            $permalink = str_replace( $parentcats, '', $permalink );
        }
    }
    return $permalink;
}

2,移除链接中子分类,比如:.com/一级分类/文章.html

//移除固定链接url中 子分类
add_filter( 'post_link', 'custom_remove_child_cats_from_link', 10, 3 );
function custom_remove_child_cats_from_link( $permalink, $post, $leavename ) {
    $cats = get_the_category( $post->ID );
    if ( $cats ) {
        usort( $cats, '_usort_terms_by_ID' );
        $category = $cats[0]->slug;
        if ( $cats[0]->parent ) {
            $permalink = str_replace( $cats[0]->slug . '/', '', $permalink );
        }
    }
    return $permalink;
}

 

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享