【发布时间】:2018-11-09 08:32:31
【问题描述】:
我无法获取下一个 url 的 id: http://www.example.com/json/compact/id/48/
我的重写代码是:
private function initHooks()
{
add_filter( 'generate_rewrite_rules', [$this,'jsonRules'] );
add_filter( 'query_vars', [$this,'jsonQueryVars'] );
add_action( 'template_redirect', [$this, 'jsonTemplate'] );
}
public function jsonRules( $wp_rewrite ) {
$wp_rewrite->rules = array_merge(
['json/(.+?)/id/(\d*)' => 'index.php?json=$matches[1]&id=$matches[2]'],
$wp_rewrite->rules
);
}
public function jsonQueryVars( $query_vars ) {
$query_vars[] = 'json';
return $query_vars;
}
public function jsonTemplate() {
echo "<pre style='position:relative;z-index:9999'>";var_dump( get_query_var( 'json' ), get_query_var( 'id' ));echo "</pre>";
}
get_query_var( 'json' ) 正在返回所需的结果,但 get_query_var( 'id') 为空
重写规则为['json/(.+?)/id/(\d*)' => 'index.php?json=$matches[1]&id=$matches[2]']
我错过了什么?
【问题讨论】:
-
我猜这是一个逃避问题,写在代码中的
\d被重写引擎接收为一个简单的d。由于令牌是可选的,因此匹配不会失败,但第二组为空。我认为\\d应该可以,但如果不是这种情况,您也可以尝试使用[0-9]而不是\d。 -
$query_vars[] = 'id';也返回这个
标签: regex wordpress url-rewriting