Categories’ hierarchy in URL

The posts in the website I’m currently working on have multiple hierarchical categories applied to each of them. For instance:

Source
- Books
-- Moby Dick
-- Sherlock Holmes

The permalinks are set as /%category%/%postname%/. However, the URL of a post does not include all subcategories – all I get is site.com/source/books/*postname*, even though the post in question has NOT been categories in Source, but only in Books + Moby Dick.

Could anyone help me figure out how to adjust this behaviour?

Thank you.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The permastruct /%category%/%postname%/ will include the categories and subcategories in the URL from top to first assigned child. So, if you want the URL be site.com/source/books/moby-dick/*postname*, you have to assign the post only to “Moby Dick”. Assigning the post only to “Moby Dick” category will still show the post under “source” and “books” category archives by default.

Method 2

Here you have a full solution, even you have multiple categories assigned to your post:

function permalink_full_categories( $cat, $cats, $post ) {

    $ordering = array();
    foreach( $cats as $index => $this_cat) {
        $ordering[$this_cat->parent] = $index;
    }

    $ordered = array();
    $i = 0;

    while( $ordering[$i] !== null ){
        array_push( $ordered, $cats[$ordering[$i]] );
        $i = $cats[$ordering[$i]]->term_id;
    }

    return end($cats);
}

add_filter( 'post_link_category', 'permalink_full_categories', 20, 3 );

It filters the permalink category changing its default behavior, returning the last category of the hierarchy.

By consequence, the WordPress core write the full hierarchy category url.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x