One of the examples using add_rewrite_rule
function in wordpress is
add_rewrite_rule('^nutrition/([^/]*)/([^/]*)/?','index.php?page_id=12&food=$matches[1]&variety=$matches[2]','top');
I can understand where matches[1] is and where matches[2] is, but is there any way to change these matches, something like:
add_rewrite_rule('^nutrition/([^/]*)/([^/]*)/?','index.php?page_id=12&food=' . f1($matches[1]) . '&variety=' . f2($matches[2]),'top');
Where f1
is a function of matches[1]
and f2
is a function of matches[2]
Thank you very much.
Edit 1:
This is a very general question with the objective to understand wordpress add_rewrite rule. One example of f1 and f2 function is
function f1($string) {
if (strpos($string, '/america/')) {$string .= '-1';}
esleif (strpos($string, '/england/')) {$string .= '-2';}
return $string;
}
f2 was a similar function to f1.
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, likedomain.com/?id=123
. The difference is that theid=
is determined by the rewrite rule, so you can have a pretty url likedomain.com/123/
. Oftentimes we’ll keep theid
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: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:The function arguments are computed at the time of function call, so when rewrite rule is being registered rather than when it is being matched and used.
You will need to do processing on matched values at different point in code.