Multiple query vars sorting combination and url rewrite
I have a custom search page for a custom post type (‘program’). There are 4 parameters that can be set up for this search: ‘word_search’, ‘archived’, ‘category’ and ‘operating_system’.
We can search by ‘word_search’ and ‘category’, or ‘operating_system’ and ‘archived’, or only ‘operating_system’ or a combination of 3 or whatever. This generates urls of the type:
- http://example.com/program/?word_search=$1&operating_system=$2&category=$3&archived=$4
If a parameter is not used for filter, it won’t be present in the final url. For example, if we don’t use the word_search nor the archived parameters, the url will look like:
- http://example.com/program/?operating_system=$1&category=$2
This works fine. Now I’d like to apply a rewrite rule like to have urls like:
- http://example.com/program/w/$1/os/$2/cat/$3/arch/$4
And all the possible combinations taking into account that some of the parameters might not be used. That is:
- http://example.com/program/w/$1/
- http://example.com/program/os/$1/cat/$2/
- http://example.com/program/w/$1/os/$2/arch/$3
- … and so on
To achieve this, I can add a rewrite rule (add_rewrite_rules), but I can’t figure out how to create the ‘generic’ url. If I only had ‘category’ parameter, I could create a rewrite rule like:
array('programs/cat/([^/]+)/?' => 'index.php?post_type=program&category=$matches[1]');
But when I have to combine 2 or more parameters, this starts to get complicated, because I have to create a line for every combination. That means:
array('programs/cat/([^/]+)/arc/([^/]+)?' => 'index.php?post_type=program&category=$matches[1]&archived=$matches[2]');
array('programs/cat/([^/]+)/os/([^/]+)?' => 'index.php?post_type=program&category=$matches[1]&os=$matches[2]');
array('programs/cat/([^/]+)/w/([^/]+)?' => 'index.php?post_type=program&category=$matches[1]&word_search=$matches[2]');
And the same for the rest of combinations. What could I do to avoid writing all the combation of rewrite rules?
Thanks!
Leave an answer