5

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?

3
  • just those 3? or is it users? Commented Feb 4, 2016 at 22:16
  • I want that any combination of letters after the /users/ to point to the same controller. there should be inifnite Urls Commented Feb 4, 2016 at 22:31
  • If you use GET then you could add the variable after /users/ to make /users/?user= and then add on your variable, but GET isn't ideal for handling stuff like usernames. I depends where your urls are originating from. Commented Feb 4, 2016 at 23:09

1 Answer 1

8

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;    

    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.