Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

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?

like image 713
Sebastian Avatar asked Feb 03 '26 23:02

Sebastian


1 Answers

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

like image 164
Sebastian Avatar answered Feb 06 '26 13:02

Sebastian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!