I have a website that lists businesses in different cities (this is a niche site, so all businesses have the same “classification”).
For starters I created a CPT for locations and a taxonomy called “Cities,” which 150 or so cities as terms.
All 300+ locations have been tagged with a city.
I was able to modify the CPT links so that they appear like so:
example.com/cityname/business-name
What I’d love to have (and not been able to accomplish yet) are urls like
example.com/cityname which would list all businesses from that city.
My understanding is that by default WP attempts to find a page with “cityname” as the name.
What would be the easiest way to reroute this request to use a taxonomy template? Or as an alternative, what would the easiest way be to have the page template detect the city name and pull posts tagged with that taxonomy term?
I suppose I could create rewrite rules in htaccess for all cities, but I’d prefer where the redirects were automatically added when a new city name is added to the taxonomy.
Here is some code that should do the trick:
Basically this creates a special permastruct that uses the slugs of the taxonomy
cities
as its base. It creates a query variable calledcityname
, which only accepts the slugs of the taxonomy and then sends the result to the proper taxonomy query variable.