Wordpress Custom Url Routing

倾然丶 夕夏残阳落幕 提交于 2019-12-11 11:08:49

问题


I have a requirement that all urls have a variable at the end and all resolve to the same controller/view

so for example we have the following URL's:

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

All three URLS should resolve to the same controller, where I would apply some logic to render each page differently based on the username.

How can I achieve this type of routing on Wordpress?


回答1:


you can use a rewrite for this...link to your controller file in the last function and call the view from there.

dont forget to visit the permalinks page and save (this flushes the rewrite rules).

    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;    

    }


来源:https://stackoverflow.com/questions/35209563/wordpress-custom-url-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!