Making extra parameters optional

I’ve setup a very specific function and it works well but I’d like to make the parameters optional but I can’t get a handle on the regex bit:

add_rewrite_rule('whats-on/([^/]+)/([^/]+)/([^/]+)/?$', 'index.php?page_id=71&event_year=$matches[1]&event_month=$matches[2]&event_day=$matches[3]','top');

/whats-on/2012/01/25 I’ll show all events on this date.

Read More

/whats-on/2012/01 goes to 404 but I’d like the parameter to be optional so I can show all January dates and the same for /whats-on/2012 all dates in year 2012

Any help will gratefully received – thanks

Related posts

Leave a Reply

3 comments

  1. Two points:

    1. Your rule isn’t particularly specific. For numeric matches you should be specific about it and specify a) digits and b) how many digits. Year would be ([0-9]{4}), month/day would be ([0-9]{1,2}).

    2. You can’t do it with one rule. Add three separate rules instead.

      add_rewrite_rule( 'whats-on/([0-9]{4})/?$', 'index.php?page_id=71&event_year=$matches[1]','top');
      add_rewrite_rule( 'whats-on/([0-9]{4})/([0-9]{1,2})/?$', 'index.php?page_id=71&event_year=$matches[1]&event_month=$matches[2]','top');
      add_rewrite_rule( 'whats-on/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/?$', 'index.php?page_id=71&event_year=$matches[1]&event_month=$matches[2]&event_day=$matches[3]','top');
      
  2. The following would be the correct regex:

    add_rewrite_rule('whats-on/([^/]+)/([^/]*)/([^/]*)/?$', 'index.php?page_id=71&event_year=$matches[1]&event_month=$matches[2]&event_day=$matches[3]','top');
    

    Notice the *s instead of +s.
    I figure in your url at least the year parameter must be supplied so I left the + unchanged there.
    Update: I checked it again and I found that there is a ? missing. here is correct pattern:

    (^whats-on/([^/]+)/([^/]*)/?([^/]*)/?$)
    
  3. I had luck with

    add_rewrite_rule('foo/bar/?([^/]+)?/?$','index.php?pagename=whatever','top');
    

    matching foo/bar, foo/bar/ but also foo/bar/optionalParam

    So called non-matching brackets (?:(/.*)) btw. do not work.
    I do not even end up correctly in the rewrite array. To check such things:

    I strongly recommend you get the (free) Monkeyman Rewrite Analyzer to see your rules in effect, and equally important, see how they compare with the regular wordpess rules as role models. Better to stick with their conventions.