WordPress internal URL routing / Rewrite API

I have a WordPress theme with Custom Post Types. My URL Structure is /%category%/%postname% (this has to stay that way)

I also have a Custom Post Type “Cars” and a Category “Cars”. When I enter domain.com/cars, WordPress will route to the archive.php template file (which is correct default behaviour).

Read More

What I want instead, is that URL pointing to the pretty URL of a page (which would have a custom template) that has the Permalink domain.com/cars (ugly URL would be domain.com/index.php?pagename=cars)

I tried this:

add_action( 'init', 'add_rewrite_rules' );  
function add_rewrite_rules() {   
    add_rewrite_rule(  
        'cars/([^/]+)/?$',  
        'index.php?pagename=$matches[1]',  
        'top');
}  

I also flushed Rewrite Rules, but it does not work (nothing happens). Any Ideas?

Related posts

Leave a Reply

1 comment

  1. I found this solution (for functions.php):

    The first line matches URLs like cars/mustang, the second one points /cars to the page named cars.

    add_rewrite_rule('^cars/([^/]*)/?','cars/$matches[1]','top');
    add_rewrite_rule('^cars$','index.php?pagename=cars','top');
    

    Don’t forget to flush the rewrite rules in Settings->Permalinks