【问题标题】:Wordpress - custom rewrite rule with optional parameterWordpress - 带有可选参数的自定义重写规则
【发布时间】:2015-06-17 22:01:02
【问题描述】:

我有以下重写规则:

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获取变量。

但是,网址的最后一部分是可选的。如果我只去mydomain.com/add/post/,我会得到 404 not found。

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

【问题讨论】:

    标签: regex wordpress rewrite


    【解决方案1】:

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

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

    Working Demo

    【讨论】:

    • 谢谢,但 url 中不必有 post。这是要编辑的项目类型,这意味着它可以是其他任何东西......
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      旧的但可能有用 - 请尝试以下模式:

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

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

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

      【讨论】:

        猜你喜欢
        • 2014-04-18
        • 2013-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-10
        • 1970-01-01
        • 2018-06-27
        相关资源
        最近更新 更多