2016-08-11 55 views
2

我正在嘗試將自定義網址結構添加到基於WordPress的網站。將WordPress地圖自定義網址轉換爲函數

例如:

example.com/machines    //list all machines in a table 

example.com/machines?some=params //list filtered machines in a table 

example.com/machines/1   //show single machine 

的數據將來自我已經開發了一個外部API,通過捲曲。

我無法將數據導入到自定義帖子類型中,因爲它在許多表上進行了規範化,業務邏輯非常複雜,並且無論如何其他設備都使用api。

我看過的文檔進行add_rewrite_rule,但第二個參數已經難倒我:

$redirect 
(string) (required) The URL you would like to actually fetch 

嗯,我沒有一個URL來獲取,我想運行一個功能,即會採取行動一個簡單的路由器 - 獲取url部分,調用外部API並返回帶有正確數據的模板。

調用API將很簡單,但我如何實際將路由到該函數,然後我如何加載模板(利用現有的WordPress header.php和footer.php)讓我難住。

回答

2

經過大量的谷歌搜索和閱讀幾個goodresources,我找到了解決方案。

的第一步是使用add_rewrite_endpoint創建將被映射到一個查詢變量基本URL:

add_action('init', function(){ 
    add_rewrite_endpoint('machines', EP_ROOT); 
}); 

訪問固定鏈接頁面刷新重寫規則後,下一步就是掛接到動作'template_redirect'真正做一些事情時,URL被擊中:

add_action('template_redirect', function(){ 
    if($machinesUrl = get_query_var('machines')){ 
     //var_dump($machinesUrl, $_GET); 
     //$machinesURl contains the url part after example.com/machines 
     //eg if url is example.com/machines/some/thing/else 
     //then $machinesUrl == 'some/thing/else' 
     //and params can be got at simply via $_GET 
     //after parsing url and calling api, its just a matter of loading a template: 
     locate_template('singe-machine.php', TRUE, TRUE); 
     //then stop processing 
     die(); 
    } 
}); 

唯一的其他東西做處理打擊沒有進一步部分的URL,例如example.com/machines到URL。 原來在一些點withing wordpresses膽,空字符串被評估爲假,因此跳過,所以最後一步是將鉤到濾波器'request',並設置一個默認值:

add_filter('request', function($vars=[]){ 
    if(isset ($vars['machines']) && empty ($vars['machines'])){ 
     $vars['machines'] = 'default'; 
    } 
    return $vars; 
}); 

這可以很容易地通過將其全部包裝在一個班級中來改進。 URL解析和模板加載邏輯可以傳遞給基本路由器,甚至是基本的MVC設置,從文件加載路由等,但上面它的起點