This is perhaps a strange question adn maybe doesn’t have answers, but I’ll try.
- custom post type: product
- custom taxonomy 1: product_category
- custom term: type1
- custom taxonomy 2: product_feature
- custom term: feature1
What I’d like:
- www.mydomain.com/products > products archive page
- www.mydomain.com/products/type1 > term archive page
- www.mydomain.com/products/feature1 > term archive page
- www.mydomain.com/products/type1/feature1 > term archive page
The main problems here I guess are 2:
- I’m bypassing the taxonomy path part (‘add_rewrite_rule’)
- Product archive and term archive share the same radix (‘products’)
Is it possible? I’m thinkin’ about several things (rest api, add_rewrite_rule/tag, etc) but not sure if they’re good/viable ways..
1 Answer
So, a first solution can be using add_rewrite_rules()
. A first raw logic should be something like:
1- get term slugs you need, save in a var, say $terms_string
; $terms_string should be a list of pipe-separeted slugs, suitable for regexp, like ‘type1|type2’ etc.. containing ONLY valid (allowed) values. Say use get_terms() to get all the slugs..
2- add a custom rewrite rule something like this:
function add_rewrite_rules() {
add_rewrite_rule(
'^products/(' . $terms_string . ')/?$', //matches things like /products/type1
'index.php?product_category=$matches[1]', //the real query that will be executed upon matching requests
'top'
);
}
add_action( 'init', 'add_rewrite_rules');
It works. It will correctly show a taxonomy archive.
In real-world cases, building a consistent rule set it will be in fact a lot more involved, but this is the way. Too much code to paste here, but I’ve just made a complex api-like set of rules, also including language management with polylang. So if someone has the same tasks, go rewriting the rules.