简体   繁体   English

WordPress的重写规则和正则表达式

[英]Wordpress rewrite rules and regex

I finally got my permalinks working for Custom Post Types and Taxonomies using ` a helper class . 我终于使用` helper class ' 使永久链接适用于自定义帖子类型和分类法。

My custom post type is "menu" and my taxonomy is "menutype". 我的自定义帖子类型是“菜单”,我的分类法是“菜单类型”。

I wrote the following rewrite: 我写了以下重写:

function custom_rewrite( $wp_rewrite ) {
    $feed_rules = array(
        'menu/salads/(.+)'    =>  'index.php?menu=' . $wp_rewrite->preg_index(1),
        'menu/hotboxes/(.+)'    =>  'index.php?menu=' . $wp_rewrite->preg_index(1),
        'menu/wraps/(.+)'    =>  'index.php?menu=' . $wp_rewrite->preg_index(1),
        'menu/sauces/(.+)'    =>  'index.php?menu=' . $wp_rewrite->preg_index(1),
        'menu/soups/(.+)'    =>  'index.php?menu=' . $wp_rewrite->preg_index(1),
        '(.+)/([^/]+)(/[0-9]+)?/?$'    =>  'index.php?menutype=' . $wp_rewrite->preg_index(2)
    );

        $wp_rewrite->rules = $feed_rules + $wp_rewrite->rules;
    }
    // refresh/flush permalinks in the dashboard if this is changed in any way
    add_filter( 'generate_rewrite_rules', 'custom_rewrite' ); 

The only thing is I would like to not hardcode the taxonomy (ie menu/sauces/, menu/hotboxes) into my rewrite rules as the terms might change (but they will always be lowercase letters) 唯一的事情是我不希望将分类法(即菜单/菜谱/,菜单/热盒)硬编码到我的重写规则中,因为术语可能会更改(但它们始终是小写字母)

I tried the following: 我尝试了以下方法:

'menu/([^/]+)/(.+)'

And also: 并且:

'menu/([a-z]+)/(.+)'

But neither worked. 但是两者都没有。

If you don't need the reference to what follows menu/ , then remove the parens there, eg 如果不需要引用menu/后面的内容,则删除其中的括号,例如

menu/[^/]+/(.+)

If you do need the reference, then make sure you're passing the correct int argument to preg_index. 如果确实需要引用,请确保将正确的int参数传递给preg_index。

As to "why does removing the parens work", because including the parens around the first group [^/]+ creates a back-reference to what's matched there. 至于“为什么删除括号会起作用”,因为将括号包括在第一组[^/]+周围会创建对此处匹配项的反向引用。 So when you call preg_index(1) you're asking for the first match, when what you want is actually the 2nd match .+ . 因此,当您调用preg_index(1)您会要求第一个匹配,而实际上您想要的是第二个匹配.+ You could also pass 2 to preg_index indicating that you want the 2nd matched group...but if you don't need the first match it's just wasted overhead to create the reference in the first place. 您还可以将2传递给preg_index指示您想要第二个匹配的组...但是,如果您不需要第一个匹配,则首先创建参考只是浪费了开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM