WordPress Custom Url Routing

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:

Read More
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?

Related posts

1 comment

  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;    
    
        }
    

Comments are closed.