Force a specific template based on the URL

When a user browses to a URI beginning with “/forums”, WordPress should call a specified template. For example, all of these URLs:

  • mysite.com/forums
  • mysite.com/forums/questions
  • mysite.com/forums/questions/1/my-question
  • mysite.com/forums/questions/ask
  • mysite.com/forums/users

… should call the following template: mytheme/page-forums.php

Read More

I believe this involves WP_Rewrite, but I have no clue what to do from here.

Any ideas?

Related posts

Leave a Reply

1 comment

  1. I’ve included some code that I use whenever I need to make additions to the WordPress rewrite rules. It injects additional rules into the normal WordPress rewrite logic so you can direct WordPress to specific template files based on the URL. You can modify it to your needs, by adding more rules to the create_rewrite_rules() function, and additional query_vars to the add_query_vars() function.

    <?php // Forums Class //
    $ForumsCode = new Forums();
    register_activation_hook( __file__, array($ForumsCode, 'activate') );
    
    add_filter('rewrite_rules_array', array($ForumsCode, 'create_rewrite_rules'));
    add_filter('query_vars',array($ForumsCode, 'add_query_vars'));
    
    add_filter('admin_init', array($ForumsCode, 'flush_rewrite_rules'));
    add_filter('template_include', array($ForumsCode, 'template_redirect_intercept'));
    
    class Forums {
    
         function activate() {
            global $wp_rewrite;
            $this->flush_rewrite_rules();
        }
    
        function create_rewrite_rules($rules) {
            global $wp_rewrite;
            $newRule = array('forums/(.+)' => 'index.php?forumdata='.$wp_rewrite->preg_index(1));
            $newRule2 = array('forums/questions/(.+)' => 'index.php?questions=true&forumdata='.$wp_rewrite->preg_index(1));
            $newRules = $newRule + $newRule2 + $rules;
            return $newRules;
        }
    
        function add_query_vars($qvars) {
            $qvars[] = 'forumdata';
            return $qvars;
        }
    
        function flush_rewrite_rules() {
            global $wp_rewrite;
            $wp_rewrite->flush_rules();
        }
    
        function template_redirect_intercept($template) {
            global $wp_query;
            if ($wp_query->get('forumdata')) {
                $template = get_bloginfo('template_url') . '/page-forums.php';
            }
            return $template;
        }
    
        function pushoutput($message) {
            $this->output($message);
        }
    
        function output( $output ) {
            header( 'Cache-Control: no-cache, must-revalidate' );
            header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
            echo json_encode( $output );
        }
    }