我正在尝试匹配以下url:
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[]根本不起作用吗?
找到了!
这篇文章来自主题。fm提到matches[n]数组只适用于正则表达式中被括号包围的组。例如:
要使$matches1在转到'planets/animals-and-more/animal/human'时返回'human',重写规则需要如下所示:
add_rewrite_rule('^planets/animals-and-more/animal/([a-zA-Z0-9-_]+)$','index.php?pagename=sponsorship&sponsorship_item=$matches[1]','top');
与()围绕你想要"匹配"的组