簡體   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