繁体   English   中英

使用 WordPress 重写规则然后使用 get_query_var 访问参数时出现问题

[英]Issues when using WordPress rewrite rules then accessing parameter using get_query_var

我正在开发一个 WP 插件并有一个 WordPress URL:

(例如: http://localhost/testsite1/coder/?id=66 ),

并尝试将重写规则添加到

http://localhost/testsite1/coder/66/

使用以下规则:

function add_mypage_rule(){
    add_rewrite_rule(
        '^coder/([0-9]+)',
        'index.php?id=$matches',
        'top'
    );
}

add_action('init', 'add_mypage_rule');

我已经使用以下方法注册了一个 WP Query Var:

add_filter('query_vars', 'registering_custom_query_var');

function registering_custom_query_var($query_vars){
    $query_vars[] = 'id';
    return $query_vars;
}

但是当我在 URL http://localhost/testsite1/coder/66/运行代码时

echo get_query_var('id');

什么都不显示

但是,当在 URL http://localhost/testsite1/coder/?id=66时, echo 语句将显示66

我的重写规则有什么问题导致echo get_query_var('id'); 没有访问参数并显示66?

  1. 当您使用add_rewrite_rule function 时,第一个参数是正则表达式。 正确的? 当您将正则表达式/模式包装在括号中时,您正在对表达式进行分组,这意味着您可以访问括号中的捕获组,如下所示: id=$matches[1]
  • 正则表达式^coder/([0-9]+)
  • 在第一个捕获的组中访问它(因为 id 在第一个括号中), id=$matches[1]
add_action('init', 'add_mypage_rule');

function add_mypage_rule()
{
    add_rewrite_rule(
        '^coder/([0-9]+)',
        'index.php?id=$matches[1]',
        'top'
    );
}
  1. 之后,通过导航到以下位置刷新永久链接并重写规则:
    Settings > Permalinks > Click on the 'Save changes' button at the bottom of the page!

现在它应该,理论上,工作,除非你在你的问题中没有提到更多的细节!


在此处输入图像描述

暂无
暂无

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

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