url rewriting – Rewrite rule to mask specific query vars with a path suffix for all pages

Question

I want to allow any page on a WP site to accept a /local/<state>/<city> suffix at the end of any path which translates into custom query vars. Other query vars should remain the same, so I don’t want to hardcode in all the parameters to rewrite into.

For example:

  • /solutions/local/il/chicago should rewrite to index.php?pagename=solutions&state=il&city=chicago
  • /solutions/local/il/chicago?foo=bar becomes index.php?pagename=solutions&state=il&city=chicago&foo=bar
  • /blog/local/il/chicago becomes index.php?post_type=post&state=il&city=chicago

Basically I want to do two rewrites in one. I want WP to parse its query vars from the URL first without my suffix, then parse my params from the suffix and add them with the existing ones.

I currently have this working now:

add_rewrite_rule(
  '^([a-z-]*)/local/([a-z]*)/([a-z-]*)$',
  'index.php?pagename=$matches[1]&state=$matches[2]&city=$matches[3]',
  'top'
);

However, this only works for top-level pages, it will not work for the home page, and it will only work for single pages but not archives or other types of pages. Plus it clears out any additional query parameters that may have been given. I want my rewrite to work on any URL so it just adds my new params on top.

0
chrispytoes 2 months 2021-06-15T16:52:57-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse