我正在尝试匹配以下网址:
planets/animals-and-more/animal/human
收件人:
index.php?pagename=animal&animal-name=human
页面“animal”有一个自定义的 page-animal.php 模板,该模板拉入“animal-name”查询变量并将其吐入 .
我已经设置了重写标签:
function animal_custom_rewrite_tag() {
add_rewrite_tag('%animal-name%', '([^&]+)');
}
add_action('init', 'animal_custom_rewrite_tag', 10, 0);
重写规则:
function add_some_rewrite_rules() {
global $wp_rewrite;
add_rewrite_rule('^planets/animals-and-more/animal/[a-zA-Z0-9]*$','index.php?pagename=animal&animal-name=$matches[4]','top');
$wp_rewrite->flush_rules();
}
add_action( 'init' , 'add_custom_ncta_rewrite_rules' );
如果我将字符串硬编码为“animal-name=monkey”,重写规则会起作用,但似乎 matches[n] 数组根本不起作用。
我知道这一切都可以通过修改 htaccess 来实现,但我需要一个适用于 Wordpress 的解决方案。
知道为什么 $matches[] 根本不起作用吗?
最佳答案
找到了!
This article from theme.fm提到 matches[n] 数组仅适用于正则表达式中被括号包围的组。例如:
获取 $matches 1要在转到“行星/动物及更多/动物/人类”时返回“人类”,重写规则需要如下所示:
add_rewrite_rule('^planets/animals-and-more/animal/([a-zA-Z0-9-_]+)$','index.php?pagename=sponsorship&sponsorship_item=$matches[1]','top');
用 () 围绕您要“匹配”的组。
关于php - Wordpress add_rewrite_rule 不返回 $matches[] 数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25166434/