wordpress如何精简子分类的url

wordpress中建了一个3级分类如下

分类
-子分类
--孙分类

现在的孙分类url如下:
www.xxx.com/fenlei/zifenlei/sunfenlei/

子分类url:
www.xxx.com/fenlei/zifenlei/

如何将孙分类/子分类的url精简如下:
www.xxx.com/zifenlei/
www.xxx.com/sunfenlei/

阅读 3.4k
2 个回答

解决了在主题文件的function.php中间中添加以下中的代码(根据自己的需求选择)

// wordpress 去掉固定链接中的子分类www.xxx.com/fenlei/zifenlei/sunfenlei/
//去掉后 www.xxx.com/fenlei/zifenlei/123.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->post_type) {
    case 'post':
        //$permalink = get_home_url() . '/' . $post->post_name . '/';
        $cats = get_the_category($post->ID);
        $subcats = array();
        foreach( $cats as $cat ) {
            $cat = get_category($cat->term_id);
            //if($cat->parent) { $subcats[] = sanitize_title($cat->name); 
            if($cat->parent) { $subcats[] = $cat->slug;}}
        if($subcats) {
            foreach($subcats as $subcat) {
                $subcat = $subcat.'/';
                $permalink = str_replace($subcat, "", $permalink);}}
        break;}
return $permalink;} 

多级分类解决方法:

// wordpress 去掉固定链接中的所有子分类包含孙分类www.xxx.com/fenlei/zifenlei/sunfenlei/
//去掉后 www.xxx.com/fenlei/123.html
function remove_child_categories_from_permalinks( $category ) {
    while ( $category->parent ) {
        $category = get_term( $category->parent, 'category' );
    }
    return $category;
}
add_filter( 'post_link_category', 'remove_child_categories_from_permalinks' );

在WebServer中(Nginx或Apache等),使用伪静态,URL重写实现。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题