FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Removing Category Base from WordPress URLs

I received the following from James, basically requesting information on how to remove the /category/ base from WordPress urls.

Hey, man. Spent quite a while on the site and i'm still having an issue with this, so i'll give it a go with you. We're using WP as a CMS with pages and posts. Done a bit of customization, so it looks sweet. Problem - i have some child categories that throw 404 when the category redirect is in place. How did you remove the category base from the url structure in wordpress? This has really got me going... thanks for being accessible!

This was one of the first hacks I figured out for WordPress, so if anyone has an improvement...

WordPress Modifications

It's very important that you replace all the links on your site to /category/slug/ to /slug/ or you will have problems. These steps should only take you a few minutes.

Removing /category/ Automatically

This is the main hack to make it work automatically throughout your site. You can place this code in your themes functions.php folder, or you can stick it in a plugin file.

function fix_slash( $string, $type )
{
    global $wp_rewrite;
    if ( $wp_rewrite->use_trailing_slashes == false )
    {
        if ( $type != 'single' && $type != 'category' )
            return trailingslashit( $string );

        if ( $type == 'single' && ( strpos( $string, '.html/' ) !== false ) )
            return trailingslashit( $string );

        if ( $type == 'category' && ( strpos( $string, 'category' ) !== false ) )
        {
            $aa_g = str_replace( "/category/", "/", $string );
            return trailingslashit( $aa_g );
        }
        if ( $type == 'category' )
            return trailingslashit( $string );
    }
    return $string;
}

add_filter( 'user_trailingslashit', 'fix_slash', 55, 2 );

category.php Theme Modifications

Here's one way to fix the url in the category.php file of your wordpress theme.

/">


.htaccess Modifications

The below .htaccess code illustrates 2 different ways to redirect any request for /category/slug/ to /slug/. You should only redirect after applying the php hacks described earlier, otherwise you could end up creating a loop.

RedirectMatch 301 ^/category/(.+)$ https://www.askapache.com/$1
# OR
RewriteRule ^category/(.+)$ https://www.askapache.com/$1 [R=301,L]

That's it!

WordPress

 

 

Comments