Wordpress - Rewrite Rules for Multiple (more than 2) Taxonomies
You could try something like this:
function custom_rewrite( $wp_rewrite ) {
$feed_rules = array(
'product-category/(.+)/material/(.+)/color/(.+)' => 'index.php?product_cat='. $wp_rewrite->preg_index(1).'&pa_material='. $wp_rewrite->preg_index(2).'&pa_color='. $wp_rewrite->preg_index(3)
'product-category/(.+)/color/(.+)' => 'index.php?product_cat='. $wp_rewrite->preg_index(1).'&pa_color='. $wp_rewrite->preg_index(2)
'product-category/(.+)/material/(.+)' => 'index.php?product_cat='. $wp_rewrite->preg_index(1).'&pa_material='. $wp_rewrite->preg_index(2)
);
$wp_rewrite->rules = $feed_rules + $wp_rewrite->rules;
}
// refresh/flush permalinks in the dashboard if this is changed in any way
add_filter( 'generate_rewrite_rules', 'custom_rewrite' );
It may not work exactly as advertised, and you might need to do some regex modifications, but that's the general gist of what needs to be done (90% of the work).
You will need to flush the permalinks if you add/edit/remove this code, put it in functions.php or a custom plugin. You can flush permalinks by simply going into the admin area and re-saving the permalinks
As a sidenote, you may run into clashing issues if you start using heirarchies,
e.g. if you have a tshirts/small and a dresses/small category, and you use a URL such as /products-category/small/color/red you might not get the results you expected, e.g. small tshirts? or did you mean small dresses?
So beware of ambiguity
For future reference (like next year when I google and find my own question again) this can be converted into add_rewrite_rule()
syntax by converting the keys in the $new_rules
array into the $regex parameter of add_rewrite_rule()
with the value as the $rewrite and 'top' as the $position.
add_rewrite_rule($regex,$rewrite, $position);
Or as an example of one of my requests from above:
function custom_rewrite() {
add_rewrite_rule(
'product-category/(.+?)/material/(.+?)/?$',
'index.php?product_cat=matches[1]&pa_material=$matches[2]',
'top'
);
}
// refresh/flush permalinks in the dashboard if this is changed in any way
add_action( 'init', 'custom_rewrite' );
For some reason I was unsuccessful using regenerate_rewrite_rules
as a hook/filter so switched to init.