Clean Custom URL for Serach + Custom Taxonomy

With Slam’s kind tip to use query-monitor plugin, I could figure out what the problem was.

Apparently the url /search/foo/filter/bar also fits the “general search” rewrite-rule. Makes sense, thinking about it– (.+) technically matches /foo/filter/bar aswell. So I could improve (.+) by excluding /s?

But I found an easier solution!

In hope “first match wins” I declared the more specific rule before the general rule– and e voila, it worked!

add_filter("rewrite_rules_array", function($rules) {

    $newRules = array();

    // more specific rule first
    $newRules["search/(.*)/filter/(.*)/?$"] = 'index.php?s=$matches[1]&filter=$matches[2]';

    // general rule later
    $newRules["search/(.+)/?$"] = 'index.php?s=$matches[1]';

    $merged = array_merge($newRules, $rules);

    return $merged;
});

error code: 523