I have a custom post type called “locations”.

I have a location called “starbucks”. I can view this by going to “/location/starbucks”.

I would like to add “coffee-shop” to the URL, so the path “/location/coffee-shop/starbucks” will load the “starbucks” page, while maintaining the URL in the browser.

i have added this code to my functions.php

function add_rewrite_rules()
{
    add_rewrite_rule('^location/([^/]*)/([^/]*)/?','index.php?pagename=$matches[2]','top');
}

add_action('init', 'add_rewrite_rules');

Which correctly loads the “starbucks” page, but it changes the URL to “/location/starbucks”.

How can I load the “starbucks” page, and keep my custom URL?

1 Answer
1

In your rewrite rule, pagename should in fact be the query_var of your custom post type. Unless you used query_var => 'something_else' in your register_post_type arguments, it’ll be the same name as your custom post type:

index.php?locations=$matches[2]

Leave a Reply

Your email address will not be published. Required fields are marked *