0

Here is my rewrite rule code:

add_rewrite_rule('tides/([^/]+)/([^/]*)', 'index.php?page_id=4348&location=$matches[1]&month=$matches[2]', 'top');
add_rewrite_tag('%location%', '([^&]+)');
add_rewrite_tag('%month%', '([^&]*)');

This works great for the following URL:

/tides/mylocation/mymonth/

but 404's on the following:

/tides/mylocation/

I'm flushing the rewrite rules every time I change the code. I tried changing * to + but no help there.

Any ideas?

Edit:

Some answers were suggesting adding another rewrite rule so I added:

add_rewrite_rule('tides/([^/]+)/$', 'index.php?page_id=4348&location=$matches[1]', 'top');

before my other rule, but still no luck.

3 Answers 3

1

Your regular expression is requiring the last slash be present which it will not be by default. So the path tides/mylocation/ is shortened to tides/mylocation and then tested. Instead, wrap the last part in an optional group using the ? and update the match number.

add_rewrite_rule('tides/([^/]+)(/([^/]+))?', 'index.php?page_id=4348&location=$matches[1]&month=$matches[3]', 'top');
1
  • That was absolutely the problem, thank you so much! Even though my permalinks end in a slash, they still get stripped before applying the regex.
    – Khan
    Commented Dec 6, 2013 at 18:55
0

Your second example URL doesn't match the pattern you defined in your rewrite rule. You need to add another rule to match URLs with just a single path element.

1
  • I used regexpal.com to test the regex and monkeyman rewrite analyzer to test it in wordpress, and it does seem to match. Doesn't the * make the second param optional?
    – Khan
    Commented Dec 6, 2013 at 17:35
0

Your initial tides rewrite rule is looking for two parameters. If you want it to accept different combinations of parameters, you need to specify those rules.

For example, these are two rules from the base Wordpress install:

search/(.+)/page/?([0-9]{1,})/?$ => index.php?s=$matches[1]&paged=$matches[2] search/(.+)/?$ => index.php?s=$matches[1]

2
  • Is there any way to match a blank parameter?
    – Khan
    Commented Dec 6, 2013 at 17:43
  • You could try doing an 'or' inside of the parameter, and match a possible empty string. For example: ([0-9]|^$)
    – ChrisLTD
    Commented Dec 6, 2013 at 17:50

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.