I'm setting up a WordPress page that would normally accept two querystring parameters. Our host prefers the use of rewrite rules instead of querystrings, so I have to take that approach.
So where I'd normally do this:
domain.com/animal-page.php?animal=dog&color=brown
I have to do this:
domain.com/animal-page/animal/dog/color/brown
The problem I am running into is that the second querystring parameter is optional.
A rewrite rule like this wouldn't work:
add_rewrite_rule(
    '([\-\w+]*)/animal/([\w+]*)/color/([\w+]*)', 
    'index.php?pagename=$matches[1]&animal=$matches[2]&color=$matches[3]',
    'top'
);  
...because if the color parameter is left off the URL (which is a possibility), that Regex fails.
I've also tried making query param (color) and value (brown) optional in the Regex, and it still doesn't work:
add_rewrite_rule( 
        '([\-\w+]*)/animal/([\w+]*)(\/color\/?)([\w+]*)',
         'index.php?pagename=$matches[1]animal=$matches[2]&$matches[3]=$matches[4]', 
        'top'
)
My question is: Is there a way to make the second query parameter optional? I want the page to react appropriately if the 'color' parameter is left off the URL.
Thanks,
In this case you will need to make two separate rules:
add_rewrite_rule(
    '([\-\w+]*)/animal/([\w+]*)/?$', 
    'index.php?pagename=$matches[1]&animal=$matches[2]',
    'top'
);  
and
add_rewrite_rule(
    '([\-\w+]*)/animal/([\w+]*)/color/([\w+]*)', 
    'index.php?pagename=$matches[1]&animal=$matches[2]&color=$matches[3]',
    'top'
);  
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With