Benjamin Charity

Remove the Parent Category from the WordPress URL

March 4th 2011

At times I've seen sites whose permalink structure looks something like this:

http://site.com/category/php/post-name/

The category parent category has no real use here and lengthens the URL for no good reason. I found this exceptional piece of code at wpsmith.net that removes this parent category from the URL with a simple addition to your functions.php file.

Add this to your functions.php file:

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;
}