Category URL to use same string as Post URL Permalink

I want to set up my site to have the following permalink structure:

/learn/%category%/%postname%

So in the permalinks section of wordpress, I set that as the custom structure. The issue is, when I click on a category page it's just:

 /%category%/

(it's ends up being a /category/subcategory/ url).

So I tried setting the category base on the permalinks setting page also to /learn/, but then I get a 404 when I go to a post's page.

How do I make it so both category pages and post pages use the /learn/ to start the url?

Topic urls permalinks options pages posts Wordpress

Category Web


The problem is that the rewrite rules overlap, WordPress is trying to find a category name that matches the post slug.

A possible solution is to do a little manual query parsing, check if the request contains category_name and is a term first, and reset query vars to post name if nothing is found:

function wpd_fix_category_requests( $request ){
    if( array_key_exists( 'category_name' , $request )
        && ! get_term_by( 'slug', basename( $request['category_name'] ), 'category' ) ){
            $request['name'] = basename( $request['category_name'] );
            unset( $request['category_name'] );
    }
    return $request;
}
add_filter( 'request', 'wpd_fix_category_requests' );

This is pretty basic, and maybe not reliable enough for primetime. Obviously you can't have a post slug that matches a category name. Also, singular post pagination won't work, and I assume attachment URLs will be broken as well.

You could fix all of those things following this method, if you were so inclined. Look at what $request contains for each type of page view, maybe with a different permalink structure so you can see what it looks like in a successful case. You just need to convert the query vars from one kind of request to the other, and WordPress will carry on loading the correct object.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.