<?php
/*
Plugin Name: Query Redirect Rewrite
Plugin URI: http://boren.nu/
Description: Example plugin demonstrating how to add query vars, load custom templates, and genereate rewrite rules.
Author: Ryan Boren
Author URI: http://boren.nu/
*/

$qrr_rewrite_tag '%qrr%';
$qrr_query_var 'qrr';
$qrr_link_base 'qrr';

// This generates the rules to handle /qrr/%qrr%/.
function qrr_generate_rewrite($wp_rewrite) {
    global 
$qrr_rewrite_tag$qrr_query_var$qrr_link_base;

    
// Add the tag, pattern, and query.  This replaces %link_category% in the
    // permalink structure with the regex ([^/]+).  The query string will
    // have link_category set to whatever the regex matched.
    
$wp_rewrite->add_rewrite_tag($qrr_rewrite_tag'([^/]+)'"{$qrr_query_var}=");
    
// Create the structure off of root.
    
$structure $wp_rewrite->root $qrr_link_base "/{$qrr_rewrite_tag}";
    
//  Make those rules
    
$rules $wp_rewrite->generate_rewrite_rule($structure);
    
// Append the rules to the rules array in the rewrite object.
    
$wp_rewrite->rules += $rules;
}

// This adds qrr as a recognized query var. It will be processed out
// of GET, PATH_INFO, or REQUEST_URI depending on how the permalink was
// requested. WP handles the particulars, you don't have to care. The value
// of qrr will be made available via the WP_Query object and
// get_query_var().
function qrr_add_query_var($vars) {
    global 
$qrr_query_var;

    
// Append qrr.
    
$vars[] = $qrr_query_var;
    
// Don't forget to return the array.
    
return $vars;
}

// If qrr is set, redirect to qrr.php.
function qrr_template_redirect() {
    global 
$qrr_query_var;
    
    
// Get the qrr from WP_Query.
    
$qrr get_query_var($qrr_query_var);

    
// If it's empty, return.
    
if (empty($qrr))
        return;

    
// Otherwise, load our template.
    // You must use load_template rather than require or include.
    // load_template() sets up the necessary environment.
    
load_template(ABSPATH "wp-content/{$qrr_query_var}.php");
    
// Make sure you exit after loading a template.
    
exit;
}

// Hook 'em in.
add_filter('query_vars''qrr_add_query_var');
add_action('generate_rewrite_rules''qrr_generate_rewrite');
add_action('template_redirect''qrr_template_redirect');
?>