0

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:

1 Answer 1

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]'
1
  • That's exactly the same as the second argument in the question isn't it?
    – Rup
    Sep 27, 2021 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.