Wordpress - 带有可选参数的自定义重写规则

Wordpress - custom rewrite rule with optional parameter

我有以下重写规则:

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;
}

如果我转到 mydomain.com/add/post/12345,页面显示正确,我通过 get_query_var 获取变量。

但是,url 的最后一部分是可选的。如果我只去 mydomain.com/add/post/,我得到 404 未找到。

我应该如何更改正则表达式以支持可选的最后一个参数?

您可以尝试使用以下正则表达式,

add\/post\/(\d+)?

Working Demo

一个简单的解决方案是添加另一条规则:

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');
}

旧模式但很有用 - 请尝试以下模式:

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

在这种情况下,parent_id 将被设置为空字符串。

我的 WP 插件中有类似的模式,它们按预期工作。