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
.
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?
One simple solution is to add another rule:
You can try using following regex,
Working Demo
Old one but can be useful – please try following pattern:
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.