I’m using url rewrites for a filter i’m building. The current solution works for one selected value. So if I select one type of dish like dinner, it goes to /recipes/dinner/.
But what if I want to filter on dinner and lunch? Is this possible, with the add_rewrite_rule?
The current solution is as followed.
add_filter( 'query_vars', function( $vars ) {
$vars[] = 'course';
return $vars;
} );
add_action( 'init', function() {
add_rewrite_tag( '%course%', '([^&]+)' );
}, 10, 0 );
add_action( 'init', function() {
add_rewrite_rule( '^recipes/([^/]*)/?', 'index.php?page_id=11&course=$matches[1]', 'top' );
}, 10, 0 );
And if it is possible what would be a logic url structure to follow?
1 Answer
As far I understand, you know are able to have an URL like example.com/recipes/dinner/
or example.com/recipes/lunch/
but now you also want to have an URL like example.com/recipes/dinner-lunch/
that pulls posts from both “dinner” and “lunch” courses.
In currents state of WP rewrites this is not possible just with add_rewrite_rule
but you also need to use pre_get_posts
to edit the query based on value catched by the rewrite rule.
For example:
add_filter('query_vars', function($vars) {
$vars[] = 'course';
return $vars;
} );
add_action('init', function() {
add_rewrite_rule('^recipes/([^/]*)/?', 'index.php?page_id=11&course=$matches[1]', 'top');
}, 10, 0);
add_action('pre_get_posts', function($query) {
if (! is_admin() && $query->is_main_query() && $query->get('course')) {
// explode the value of matched course by -
$courses = explode('-', $query->get('course'));
// update the value in query with an array
$query->set('course', $courses);
}
});
The issue here is that if a “course” has an hyphen in the name, the explode
will break the query, so maybe you can use a less common separator.