1

Wordpress Category Archive permalinks set up with %category% include the full category tree. I want to see only the leaf category in the URL, not the full tree.

Example:

Wordpress Category: recipes > baking > bread
current permalink for archive: domain.com/recipes/baking/bread
desired permalink: domain.com/bread

I've been searching the web without any idea how to hook or filter this change into my wordpress code, so any ideas and help is highly welcome. thanks Jan

1

2 Answers 2

0

You can filter term_link to modify any taxonomy URL generated by the API. In this case, we only need the filter, as the default rewrite rules will handle this modification for the incoming requests. If you're doing any sort of change that introduces a new URL pattern, you will also need to add new rules or change the existing ones so these new URLs can successfully parse into the correct queries and not just 404.

If you look at the get_term_link API function source, you will see the branch where it checks if it's a hierarchical taxonomy. I just copy/pasted some bits from the non-hierarchical case so the output is the same as a non-hierarchical term.

add_filter( 'term_link', 'wpd_term_link_filter', 10, 3 );
function wpd_term_link_filter( $url, $term, $taxonomy ) {
    if( 'category' == $taxonomy ){
        global $wp_rewrite;
        $termlink = $wp_rewrite->get_extra_permastruct( $taxonomy );
        $termlink = str_replace( "%$taxonomy%", $term->slug, $termlink );
        $url = home_url( user_trailingslashit($termlink, 'category') );
    }
    return $url;
}
1
  • Thanks Milo, I found a similar solution (see my answer below) thanks to your explanation. Works now like a charm!
    – Jan
    Commented Jul 21, 2018 at 21:46
0

After some searching I found the answer, in case someone else has a similar issue. The following code will leave only the deepest category in the archive permalink and will remove all parent categories.

add_filter( 'category_link', 'wpse7807_category_link', 10, 2 );
function wpse7807_category_link( $catlink, $category_id )
{
    global $wp_rewrite;
    $catlink = $wp_rewrite->get_category_permastruct();

    if ( empty( $catlink ) ) {
        $catlink = home_url('?cat=' . $category_id);
    } else {
        $category = &get_category( $category_id );
        $category_nicename = $category->slug;

        $catlink = str_replace( '%category%', $category_nicename, $catlink );
        $catlink = home_url( user_trailingslashit( $catlink, 'category' ) );
    }
    return $catlink;
}

kudos to Changing the category permalink structure.

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.