3

我正在开发一个 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;
}

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

echo get_query_var('id');

什么都不显示

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

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

4

1 回答 1

3
  1. 使用add_rewrite_rule函数时,第一个参数是正则表达式。对?当您将正则表达式/模式包装在括号中时,您正在对表达式进行分组,这意味着您可以访问括号中捕获的组,如下所示id=$matches[1]
  • Regular expression ^coder/([0-9]+)
  • Access it in the first captured group (since the id is in the first parenthesis), 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. After that, refresh the permalinks and rewrite rules by navigating to:
    Settings > Permalinks > Click on the 'Save changes' button at the bottom of the page!

And now it should, theoretically, work, unless there are more details that you have not mentioned in your question!


enter image description here

于 2022-01-18T22:29:19.040 回答