2016-02-04 80 views
1

我有所有的URL都在最後一個變量,都決心在同一控制器/要求視圖WordPress的自定義URL路由

因此,例如,我們有以下網址:

http://example.com/users/joe 
http://example.com/users/sam 
http://example.com/users/jack 

所有三個URL應該解析爲同一個控制器,我將根據用戶名應用一些邏輯來呈現每個頁面。

如何在Wordpress上實現此類路由?

+0

只是那3個?還是用戶? – David

+0

我希望/ users /之後的任意字母組合指向相同的控制器。應該有inifnite Url –

+0

如果你使用'GET',那麼你可以在'/ users /'之後添加變量來製作'/ users /?user =',然後添加你的變量,但是'GET'不適合處理用戶名等內容。我取決於你的網址來自哪裏。 – Steve

回答

2

您可以使用此重寫...鏈接到最後一個函數中的控制器文件,並從那裏調用視圖。

不要忘了訪問永久鏈接頁面並保存(這刷新了重寫規則)。

add_action('init', 'anew_rewrite_rule'); 
    function anew_rewrite_rule(){ 
     add_rewrite_rule('^users\\/[a-z]','index.php?is_customusers_page=1','top'); 
    } 

    add_action('query_vars','controller_set_query_var'); 
    function controller_set_query_var($vars) { 
     array_push($vars, 'is_customusers_page'); // ref url redirected to in add rewrite rule 

     return $vars; 
    } 


    //we'll call it a template but point to your controller 
    add_filter('template_include', 'include_controller'); 
    function include_controller($template){ 


     // see above 2 functions.. 
     if(get_query_var('is_customusers_page')){ 
      //path to your template file 
      $new_template = get_stylesheet_directory().'/controllerpath.php'; 
      if(file_exists($new_template)){ 
       $template = $new_template; 
      } 
     }  

     return $template;  

    } 
+0

是否適合你? – David