How to remove category from wordpress url structure

There are many WordPress blog owner out there who do not pay close attention to the structure of their urls. If you’re a avid WordPress user then you may have notice that WordPress allows you to specify custom permalink structure for your urls. I am not sure what most blog owners use but I mostly think everyone used the:

/%category%/%postname%/

If you’re using the above structure from your permalinks then you may have noticed that wordpress adds category into your email.

Example:

http://www.yoursite.com/category/postname

You would like the url to look like this.

Example:

http://www.yoursite.com/postname

This can be achieved using wordpress. Add the following code below 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;
}

The code above tells WordPress that any url that is using the word category to remove category and rewrite the url without the category. This method is a cleaner approach then editing the .htaccess file since some WordPress owners have no experience editing the .htaccess file.

Razvan Sava the author

Razvan is the founder of Webdevtuts. He is also a web designer & developer who loves to design and develop websites. If you're looking for him you can find him via @webdevtuts

Leave a Reply