How to change the matches in add_rewrite_rule

Rewrite rules don’t call functions like you’re asking. WordPress is far more flexible than that, because you might want to run your code at any one of an unlimited set of points in the processing of the page and not be restricted to that one specific moment in the code when the rewrite rule is processed.

Taking it back a step, rewrite rules are meant to work just like $_GET does, where you can pass data through the URL, like domain.com/?id=123. The difference is that the id= is determined by the rewrite rule, so you can have a pretty url like domain.com/123/. Oftentimes we’ll keep the id in the URL, e.g. domain.com/id/123/ to avoid conflicts with other URL structures, but that’s not important for the sake of this answer.

Using your example, say you had a rewrite rule for nations, and you wanted your URLs to look like /nation/america/ or /nation/england/. Here is an example rewrite rule for this:

add_rewrite_rule( '^nation/([^/]*)/?', 'index.php?nation=$matches[1]' );

To use this information, you can pretty much hook into any action or filter after parse_query. That’s the first action available after the query vars are set, so it’s the first action where you can use get_query_var. Here’s an example:

function wpse_99414_get_nation() {
    if ( $nation = get_query_var( 'nation' ) ) {
        # This is the equivalent to your f1 function
        # $nation will either be 'america', 'england', or whatever else
        # process it however you need!
    }
}
add_action( 'parse_query', 'wpse_99414_get_nation' );

Lastly, note that in order to use a custom query var like how we used nation, you need to register it. Here’s an example of doing that:

function wpse_99414_query_vars( $qv ) {
    $qv[] = 'nation';
    return $qv;
}
add_filter( 'query_vars', 'wpse_99414_query_vars' );

Leave a Comment