Remove /category/ From Category URLs
Shortens category links from example.com/category/news/ to example.com/news/ and redirects the old addresses there permanently.
Opens WPIDE on
Code
add_filter( 'category_link', function ( $link ) {
$base = trim( get_option( 'category_base' ) ? get_option( 'category_base' ) : 'category', '/' );
return str_replace( home_url( '/' . $base . '/' ), home_url( '/' ), $link );
} );
add_filter( 'category_rewrite_rules', function () {
$rules = array();
foreach ( get_categories( array( 'hide_empty' => false ) ) as $category ) {
$path = $category->parent ? get_category_parents( $category->term_id, false, '/', true ) : $category->slug . '/';
if ( is_wp_error( $path ) ) {
continue;
}
$path = preg_quote( trim( $path, '/' ), '#' );
$rules[ "($path)/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$" ] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
$rules[ "($path)/page/?([0-9]{1,})/?$" ] = 'index.php?category_name=$matches[1]&paged=$matches[2]';
$rules[ "($path)/?$" ] = 'index.php?category_name=$matches[1]';
}
// Old /category/... addresses are caught and redirected below.
$base = trim( get_option( 'category_base' ) ? get_option( 'category_base' ) : 'category', '/' );
$rules[ preg_quote( $base, '#' ) . '/(.+?)/?$' ] = 'index.php?wpide_old_category=$matches[1]';
return $rules;
} );
add_filter( 'query_vars', function ( $vars ) {
$vars[] = 'wpide_old_category';
return $vars;
} );
add_action( 'template_redirect', function () {
$old = get_query_var( 'wpide_old_category' );
if ( $old ) {
wp_safe_redirect( home_url( '/' . trim( sanitize_text_field( $old ), '/' ) . '/' ), 301 );
exit;
}
} );
// Rebuild the rules when categories change.
foreach ( array( 'created_category', 'edited_category', 'delete_category' ) as $wpide_cat_hook ) {
add_action( $wpide_cat_hook, function () {
delete_option( 'rewrite_rules' );
} );
}
Notes
Needs pretty permalinks; visit Settings > Permalinks once after activating and avoid categories with the same slug as a page, since the category wins.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.