【问题标题】:Get the id with wp_rewrite rules使用 wp_rewrite 规则获取 id
【发布时间】: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*)' =&gt; 'index.php?json=$matches[1]&amp;id=$matches[2]']

我错过了什么?

【问题讨论】:

  • 我猜这是一个逃避问题,写在代码中的\d被重写引擎接收为一个简单的d。由于令牌是可选的,因此匹配不会失败,但第二组为空。我认为\\d 应该可以,但如果不是这种情况,您也可以尝试使用[0-9] 而不是\d
  • $query_vars[] = 'id';也返回这个

标签: regex wordpress url-rewriting


【解决方案1】:

尝试添加这个

public function jsonQueryVars( $query_vars ) {
        $query_vars[] = 'json';
        $query_vars[] = 'id';
        return $query_vars;
    }

【讨论】:

    猜你喜欢
    • 2012-10-19
    • 2011-05-15
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多