URL rewrite rules for multiple taxonomies query

The question:

I’m trying to create some pretty URLs for links querying multiple taxonomies. I’m using the “Taxonomy drill-down” plugin, although the main usage is now integrated @ the core it still has some helpful function for templating 🙂

An example URL querying multiple taxonomies ( working ) would be:
domain.com/?tax1=foo&tax2=bar

My goal is to have links like –
domain.com/tax1/foo/tax2/bar – translating to the above example

tax1/2 = taxonomy name

foo/bar = required term

I stumbled upon Examples of WP Rewrites but i think i suck with those patterns and something like:

$newrules['tax1/(.*)/tax2/(.*)/'] = 'index.php?tax1=$matches[1]&tax2=$matches[2]';

doesn’t seem to work ( that’s just a portion of the whole function based on the WordPress example )

Any ideas? 🙂

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

(.*) matches everything, so it will “eat up” the extra characters (it is “greedy”). If the URL is /tax1/foo/tax2/bar/, the first (.*) will be foo/tax2/bar/, so nothing is left for the second match.

Instead of (.*) you can use the “non-greedy” version (.+?). This will match as much as possible, but still keep the rest in mind. You can also use the even stricter version ([^/]+): this will match everything up to the next / – but this will not work for nested categories, so /category/fruit/banana/tag/flies/ will not split up in fruit/banana and flies like you might expect.

If you are going to play with the rewrite rules I recommend you to install my Rewrite analyzer plugin. It allows you to see the current rewrite rules and play with URLs to see which rules will match.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment