2

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?

  • Try location=$matches[2], not pagename. – TheDeadMedic Jun 7 '14 at 10:20
  • @TheDeadMedic that loaded the homepage. – Corey Jun 7 '14 at 10:23
  • Whoops, try locations instead (note the plural). – TheDeadMedic Jun 7 '14 at 10:24
  • Yes, that did it. Thanks! Please add your comment as an answer, and I'll accept it. – Corey Jun 7 '14 at 10:29
  • Nice one. Will do. – TheDeadMedic Jun 7 '14 at 10:33
3

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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.