3

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.

2 Answers 2

3

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.

0
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.