WPSurfer.com

How To Remove the Category From the WordPress URL

Published on December 10, 2022 | Updated on December 19, 2022

To remove a category base in WordPress, you can use the remove_action function in your theme’s functions.php file. Here’s an example of how you can do this:

function remove_category( $string, $type )  {           if ( $type != 'single' && $type == 'category' && ( strpos( $string, 'category' ) !== false ) )          {              $url_without_category = str_replace( "/category/", "/", $string );              return trailingslashit( $url_without_category );          }      return $string;  }     add_filter( 'user_trailingslashit', 'remove_category', 100, 2);

This code will remove the default “category” base from your category permalinks so that your URLs will not include the base. For example, if your category’s slug is “news”, the URL of the category will be http://yoursite.com/news instead of http://yoursite.com/category/news.

Note that this will only work if you are using pretty permalinks in WordPress. To enable pretty permalinks, go to Settings > Permalinks in your WordPress admin dashboard and select a permalink structure that includes the post name (e.g. http://yoursite.com/sample-post/).

GeneratePress Custom Category Pages

If you are using custom category pages, you should also add this code to your functions.php file

add_filter('request', function( array $query_vars ) {
    if ( is_admin() ) {
        return $query_vars;
    }

    if ( isset( $query_vars['category_name'] ) ) {
        $pagename = $query_vars['category_name'];

        $query_vars = array( 'pagename' => "$pagename" );
    }

    return $query_vars;
} );
Manuel Campos

Manuel Campos

I am José Manuel. I am writing about things I know and things that I am learning about WordPress. I hope you find the content of this blog useful.

WP SURFER

home

about

privacy

contact

© 2024 WP SURFER • Made with Love in Costa Rica