Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress - Rewrite rules with multiple parameters

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,

like image 484
Kyle Dowling Avatar asked Mar 16 '23 19:03

Kyle Dowling


1 Answers

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'
);  
like image 81
14 revs, 12 users 16% Avatar answered Mar 27 '23 21:03

14 revs, 12 users 16%