Remove Child Category in Permalink WordPress

Đây là một đoạn code nhỏ mình dùng để tinh chỉnh lại permanlink bài viết trong WordPress.

Mô tả

Với một bài viết có nhiều category và được cấu hình Permalink trong Setting WordPress như sau:

  • https://www.vietrick.com/%category%/%postname%/

Đường dẫn mặc định sẽ là:

  • https://www.vietrick.com/top-category/level1-cate/level2-cate/post-slug

Remove Child Category in Permalink

Remove Child Category in Permalink

Đoạn code bên dưới sẽ có tác dụng xóa hết các child category trên đường dẫn URL và chỉ giữ lại top-category

https://www.vietrick.com/top-category/post-slug

Các bạn chèn đoạn sau vào nội dung tệp functions.php trong theme đang sử dụng. Sau đó đến setting Permalinks trong phần quản trị WordPress và nhấn Save Changes để refresh lại permalink.

/*
* 
* Remove child categories from permalink in Wordpress
* https://www.vietrick.com/remove-child-category-in-permalink/
*
*/

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', 999 );
// Wordpress Settings > Permalinks > Save Changes to refresh.
No Comment
Add Comment
comment url