WordPress – custom rewrite rule with optional parameter

I have following rewrite rule:

add_action('init', 'custom_rewrite_rule', 10, 0);
function custom_rewrite_rule() {
    add_rewrite_rule('^add/([^/]*)/([^/]*)/?','index.php?page_id=2436&type=$matches[1]&parent_id=$matches[2]','top');
}

add_filter('query_vars', 'foo_my_query_vars');
function foo_my_query_vars($vars){
    $vars[] = 'type';
    $vars[] = 'parent_id';
    return $vars;
}

If I go to mydomain.com/add/post/12345, the page is displayed correctly and I get the variables via get_query_var.

Read More

However, the last part of the url is optional. If I go just to mydomain.com/add/post/, I get 404 not found.

How should I change the regex to support the optional last parameter?

Related posts

Leave a Reply

3 comments

  1. One simple solution is to add another rule:

    function custom_rewrite_rule() {
        add_rewrite_rule('^add/([^/]*)/([^/]*)/?','index.php?page_id=2436&type=$matches[1]&parent_id=$matches[2]','top');
        add_rewrite_rule('^add/([^/]*)/?','index.php?page_id=2436&type=$matches[1]','top');
    }
    
  2. Old one but can be useful – please try following pattern:

    function custom_rewrite_rule() {
        add_rewrite_rule('^add/([^/]*)/?([^/]*)?','index.php?page_id=2436&type=$matches[1]&parent_id=$matches[2]','top');
    }
    

    In this case parent_id will be set to empty string.

    I’ve similar patterns in my WP plugin and they are working as expected.