Site icon WP Smith

How to Remove the Category Base URL in WordPress (via kmsm)

Courtesy of Joshua Kelly of kmsm.ca

One of the difficulties with using WordPress as a CMS is that the out-of-the-box URL construction is limited. In this respect, categories have particularly poor control.

By default, WordPress constructs category URLs as http://domain/category/category-name and post URLs as http://domain/date/post-name. While you can control most aspects of the post URLs (whether or not to display the month of the post, for example), the only customization available for category URLs is the base name following the domain in which all categories reside (http://domain/series/category-name, for example).

But this can lead to counterintuitive URLs.

For example, if I file a post about about the Godather under a category called Film, the post URL will read http://domain/2010/01/01/the-godfather while the category URL will read http://domain/category/film. This might work well for a blog format, but for large-scale content management, intuitive URLs are a big deal.

Thankfully, we can get WordPress to do our bidding with a simple hack – and it even works with WordPress 3.0!

Let’s say I want to create post URLs in the form http://domain/category/post-name and category URLs in the form http://domain/category-name. Makes sense right? Well here’s how we do that.

Step One: Edit the Post Permalink

Open up WordPress administration panel, and navigate to the Permalinks options screen. Under Common settings, click Custom Structure and enter /%category%/%postname%/ into the field.

Step Two: Edit Functions.php

To edit the category URL structure we have to go into the functions.php file in our WordPress theme. Before the closing PHP bracket, enter the following:
[php]
add_filter('user_trailingslashit', 'remcat_function');
function remcat_function($link) {
return str_replace("/category/", "/", $link);
}

add_action('init', 'remcat_flush_rules');
function remcat_flush_rules() {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}

add_filter('generate_rewrite_rules', 'remcat_rewrite');
function remcat_rewrite($wp_rewrite) {
$new_rules = array('(.+)/page/(.+)/?' => 'index.php?category_name='.$wp_rewrite->preg_index(1).'&paged='.$wp_rewrite->preg_index(2));
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

[/php]
Make sure to save functions.php and upload it to the theme directory.

Now, to go back to the Godfather example, category URLs will look like http://domain/film and post URLs will appear as http://domain/film/the-godfather. Cool eh?

There are other ways of doing this using .htaccess but this is a cleaner approach in that it modifies how WordPress generates URLs, instead of modifying how the server interprets them.