admin管理员组

文章数量:1279145

Using add_rewrite_rule() to handle things like this for the custom post type "catalogs", page name "cars":

/catalogs/cars/ /catalogs/cars/p1/ /catalogs/cars/p1/p2/ /catalogs/cars/p1/p2/p3/

I never have more than 3 parameters after /cars/, but all of them with optional query string parameters. Like this:

/catalogs/cars/p1/p2/?weight-max=3200

Here's my code:

add_rewrite_rule( 
    '^catalogs/([^/]*)/([^/]*)/([^/]*)/([^/]*)/?', 
    'index.php?catalogs=$matches[1]&p1=$matches[2]&p2=$matches[3]&p3=$matches[4]', 
    'top'
);

Works great for when there's 3 parameters (like /catalogs/cars/p1/p2/p3/), but it doesn't work for when there's 0-2 parameters.

Have tried making parts of the regex optional, but I guess my regex skills aren't that fantastic...

Have a trick for making the number of parameters dynamic, so everything from 0-3 parameters can be handled?

Thanks :thumbsup:

Using add_rewrite_rule() to handle things like this for the custom post type "catalogs", page name "cars":

/catalogs/cars/ /catalogs/cars/p1/ /catalogs/cars/p1/p2/ /catalogs/cars/p1/p2/p3/

I never have more than 3 parameters after /cars/, but all of them with optional query string parameters. Like this:

/catalogs/cars/p1/p2/?weight-max=3200

Here's my code:

add_rewrite_rule( 
    '^catalogs/([^/]*)/([^/]*)/([^/]*)/([^/]*)/?', 
    'index.php?catalogs=$matches[1]&p1=$matches[2]&p2=$matches[3]&p3=$matches[4]', 
    'top'
);

Works great for when there's 3 parameters (like /catalogs/cars/p1/p2/p3/), but it doesn't work for when there's 0-2 parameters.

Have tried making parts of the regex optional, but I guess my regex skills aren't that fantastic...

Have a trick for making the number of parameters dynamic, so everything from 0-3 parameters can be handled?

Thanks :thumbsup:

Share Improve this question asked Sep 25, 2021 at 13:35 MadsMads 11 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

Found the solution, just had to remember all the ? marks.

It works when the regex is like this:

'index.php?catalogs=$matches[1]&p1=$matches[2]&p2=$matches[3]&p3=$matches[4]'

本文标签: url rewritingaddrewriterule with optional parameters