Custom URL routing based on cookie value

SESSION variables aren’t reliable, and won’t work on some WP hosts. Even worse, you’re going to prevent caching

But more importantly, don’t route, redirect! Routing and redirecting are not the same thing

So, we want the following logic:

  • on the template_redirect action
    • if the user is on the homepage aka is_home
      • call wp_safe_redirect redirect to the closest office page
      • call exit

I’d want to set a session var when it doesn’t exists yet containing the selected location so that I can redirect subsequent page requests to a sub page of that location.

But you have their IP, which you’re using to figure out their location, why not just use that?

The user is requesting the Contact page: http://example.com/contact What hook would I need to use to be able to rewrite that URL to http://example.com/locations/new-york/contact in case the session var is set?

Be careful, when you say rewrite, it’s not the same as redirecting. If I visit example.com/foo, and it gets rewritten to example.com/bar in PHP, it will still say /foo in my browser. You haven’t moved me to /bar, you’ve changed what content displays at /foo. Redirect the user.

You might think I’m quibbling, but rewriting is a different thing, with a different set of APIs, that solves a completely different problem. The same with routing. Routing figures out given a URL which code should I load. Your problem is “Given a URL and a location, where should I redirect the user to”

So, on the contact page, before you output any HTML, test the user location and use wp_safe_redirect then exit