How do I append multiple taxonomies to the URL?

This is certainly possible by utilizing some rewrite rules of your own to some extent. The WP_Rewrite API exposes functions that allow you to add rewrite rules (or ‘maps’) to convert a request to a query.

There are prerequisites to writing good rewrite rules, and the most important one is basic regular expression comprehension. The WordPress Rewrite engine uses regular expressions to translate parts of a URL to queries to get posts with.

This is a short and good tutorial on PHP PCRE (Perl compatible regular expressions).

So, you’ve added two taxonomies, let’s assume their names are:

  • product_type
  • product_brand

We can use these in queries like so:

get_posts( array(
    'product_type' => 'cell-phones',
    'product_brand' => 'samsung'
) );

The query would be ?product_type=cell-phones&product_brand=samsung. If you type that as your query you will get a list of Samsung phones. To rewrite /cell-phones/samsung into that query a rewrite rule must be added.

add_rewrite_rule() will do this for you. Here’s an example of what your rewrite rule might look like for the above case:

add_rewrite_rule( '^products/([^/]*)/([^/]*)/?',
    'index.php?product_type=$matches[1]&product_brand=$matches[2]',
    'top' );

You will need to flush_rewrite_rules() as soon as you’ve added the rewrite rule to save it to the database. This is done only once, there is no need to do this with every request, once a rule is flushed its there. To remove it simply flush without the added rewrite rule.

If you want to add pagination you can do so by doing something like:

add_rewrite_rule( '^products/([^/]*)/([^/]*)/(\d*)?',
    'index.php?product_type=$matches[1]&product_brand=$matches[2]&p=$matches[3]',
    'top' );

Leave a Comment