3

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?

  • 2
    What do you mean by "…if I want to filter on dinner and lunch¿" – kaiser May 30 '16 at 10:33
  • The most filters use a get variable to filter on more taxonomies, something like ?course=dinner,lunch But with url rewrite, you can't and don't want to use /recipes/dinner/lunch What would be a good SEO approach? Something like /recipes/dinner-lunch/ or is it better to simple use a get variable? – Roy May 31 '16 at 11:52
  • 1
    Please use edits to answer and clarify instead of comments. Thanks. And SEO topics are better asked on webmasters.stackexchange.com – kaiser May 31 '16 at 11:58
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.