How to remove the Category Base from WordPress paths

Every now and then I get asked how to get rid of the “category” base from their WordPress URL so that myblog.com/category/snowboarding becomes myblog.com/snowboarding.

The Simple Solution

Luckily, there’s a plugin that can do this for you named FV Top Level Categories with no hassles or settings to mess with. Just install, activate and you’re good to go.

Glutton for Punishment?

You can also achieve the same thing with no plugin too.

The trick to removing the category base is to go to Settings > Permalinks and set the following:

  1. Custom Structure to /%category%/%postname%/
  2. Category base to .

The Problem

Everything seems to work until you try to go to page two of your Category archives myblog.com/snowboarding/page/2 and it takes you to a 404 page not found error.

Now, that sucks. What’s happening here is that /page/2 is conflicting with the custom permalink structure.

How do I fix it?

First, when you investigate the request, you find that there is an additional key of ‘name’ in the query that is not present with a normal paged archive. So one method to go about this is to remove the offending key before WordPress tries to process the request.

You can do this by adding the following code to your functions.php of your theme:

function mytheme_request($query_string ) {
  if( isset( $query_string['page'] ) ) {
    if( !empty($query_string['page']) ) {
      if( isset( $query_string['name'] ) ) {
        unset( $query_string['name'] );
      }
    }
  }
  return $query_string;
}
add_filter('request', 'mytheme_request');

Not quite there

When you test the code, you will find that you no longer get a 404 error. Great! But hold on, you will now notice that the paging takes you back to the first page over and over again.

What’s happening here is that the page number is not being provided to the WordPress query. So in the follow code snippet, we will take the page number from the path and set it in the WordPress query.

function mytheme_pre_get_posts( $query ) {
  if( $query->is_main_query() && !$query->is_feed() && !is_admin() ) {
    $query->set( 'paged', str_replace( '/', '', get_query_var( 'page' ) ) );
  }
}
add_action('pre_get_posts','mytheme_pre_get_posts')

Again, add this code to your functions.php and then try it out.

Viola! You’re Now Set

Not impressed? Or just feeling lazy? I’m surprised you made it this far then. If you missed it, there is also a plugin available that helps you remove the category base with no fuss.

Have a question or want to say hi?

Send me an email or find me on: