Use add_rewrite_rule(). The examples on the document page should get you pretty close. The problem you can run into with this is having your rewrite applied when it shouldn’t. This is a problem any time the regexp extracts parameters based on position alone. It’s very useful to have something fixed as a “base” so that the rewrite can only be applied when the base is present.
The base doesn’t have to be a single value, but the options are limited. For example, if your only regions are Europe and Asia, that can be accommodated. If the base were to be every country in the world OTOH, they would be very difficult to use as a base.
Hi @bcworkz
Thanks a lot for the answer.
This seems a little bit far from my coding knowledge.
I have 7 regions ( AFRICA, ASIA,CANADA, CENTRAL AND SOUTH AMERIA, EUROPE, OCEANIA, THE CARIBBEAN, USA)
So your proposing to create a “base” for all the regions. this would be what I have to put in $regex?
and $redirect would be in my case this: ‘/?s=&city=$city’ ?
If you could guide me with more details would be nice since I’m not a programmer.
Thanks
Hmmm, 7 regions could still work, but it’s getting cumbersome. If you could see your way into putting something that’s fixed into the URL, it would be better. As in example.com/region/europe/paris/ or even just example.com/r/europe/paris/. Alternately, ending the region parameter with a fixed value, like example.com/europe-region/paris/ achieves the same end. Of course, it doesn’t need to be region. It could be “area”, “zone”, “foo”, anything consistent.
function custom_rewrite_rule() {
add_rewrite_rule('^region/[^/]*/([^/]*)/?','index.php?s=&city=$matches[1]','top');
}
add_action('init', 'custom_rewrite_rule');
If you want to experiment with a different regexp, try regexr.com. Because of a slightly different application, don’t include the initial ‘^’, and slashes need to be escaped with a backslash: ‘\/’. The OR operator is a pipe ‘|’, as in ‘asia|europe’. Hover over matches for more information. The group # shown is the number used in $matches[#].
It’s important that non-applicable URLs never match, as in example.com/category/paris/