Search code examples
regexwordpressmod-rewriteurl-rewriting

Regex rewrite rule


I have following rewrite rule implemented in the website

add_rewrite_tag('%c%', '([^&]+)');
add_rewrite_rule('^blog/([a-z0-9-]+)[/]?', 'index.php?pagename=blog&c=$matches[1]', 'top');

It works when I have the exact match, for example

https://example.com/blog/category

But when URL contains any query parameter it does not match

https://example.com/blog/category?utm_campaign=web

I want to match and retain any query parameter from the URL if exist, how do I go about it?

Thanks


Solution

  • We need to define the query parameter key by using add_rewrite_tag(...); probably because of this, we cannot declare an unknown number of query parameters. If someone has another solution, I would be happy to learn it. The following code is for only the "utm_campaign" parameter.

    add_rewrite_tag('%c%', '([^&]+)');
    add_rewrite_tag('%utm_campaign%', '([^&]+)');
    
    add_rewrite_rule('^blog/([a-z0-9-]+)[/]?(?:[?].*utm_campaign=([^&\s]+))?', 'index.php?pagename=blog&c=$matches[1]&utm_campaign=$matches[2]', 'top');