Yes, it is possible.
Add the rewrite rule:
/* The rule matches:
* example.com/product-category/rings/rings-in-gold/
* example.com/product-category/rings/rings-in-gold/page/<number>/
*/
add_action( \'init\', function () {
add_rewrite_rule(
\'^product-category/rings/rings-in-gold(?:/page/(\\d+)|)/?$\',
// $matches[1] is the (\\d+) (page number) from the above Regex, if any.
\'index.php?product_cat=rings&filter_material=gold&paged=$matches[1]\',
\'top\'
);
} );
For other categories, just copy the above add_rewrite_rule()
and replace the text "rings", "rings-in-gold" and "gold".
Register the custom query var filter_material
:
add_filter( \'query_vars\', function ( $vars ) {
$vars[] = \'filter_material\';
return $vars;
} );
You can use another name for the query var, but make sure the name does not already exist.
Flush/regenerate the rewrite rules — just visit the permalink settings page.
And then in your theme/template, you can get the "material" filter value like so:
$material = get_query_var( \'filter_material\' );
I\'m not the author of the plugin and I have no affiliation with him or the plugin, but it\'s an awesome plugin with a user-friendly UI for creating redirections, both standard ones (where the URL in the browser\'s address bar changes) and pass-through which works like the add_rewrite_rule()
, i.e. no URL change.
The plugin also comes with cool features such as tracking, so if you like that and don\'t want to mess with coding, then you can check here how to use the plugin. But here\'s an example based on the add_rewrite_rule()
example above:
Create a new redirection.
Apply these settings: (click the cog icon to see the "When matched" option)
Source URL: /product-category/rings/rings-in-gold(?:/page/(\\d+)|)/?$
Regex: Yes (check the box)
When matched: Pass-through
Target URL: /product-category/rings/?filter_material=gold&paged=$2
Once again, for other categories, just replace the relevant text.
With this plugin, you don\'t need to register the custom query var (see step #2 in Option 1 above) and simply use $_GET[\'filter_material\']
in your theme/template:
// Simplified example in PHP 7 syntax.
$material = $_GET[\'filter_material\'] ?? \'\';
Note: Before you try the second option, make sure to edit your file and remove the code taken from Option 1 and visit the permalink settings page. Alternatively, use another category (e.g. earrings
) when testing the second option. This is so that you know both options actually work. :)