Create built-in pages without creating actual pages

This is the technique I’m using on a site right now. It involves registering a query var for “template”, and registering an endpoint called /contact, which rewrites internally to ?template=contact. Then you just check for that query variable at the template_redirect hook, and if its present, include the page template you want to load and exit.

/* Add a query var for template select, and and endpoint that sets that query var */
add_action( 'init', 'wpse22543_rewrite_system' );

function wpse22543_rewrite_system() {
    global $wp, $wp_rewrite;
    $wp->add_query_var( 'template' );   
    add_rewrite_endpoint( 'contact', EP_ROOT );
    $wp_rewrite->add_rule(  '^/contact/?$', 
                            'index.php?template=contact', 'bottom' );
    $wp_rewrite->flush_rules();
    }


/* Handle template redirect according the template being queried. */
add_action( 'template_redirect', 'wpse22543_select_template' );

function wpse22543_select_template() {
    global $wp;
    $template = $wp->query_vars;

    if ( array_key_exists( 'template', $template ) && 
        'contact' == $template['template'] ) {
        /* Make sure to set the 404 flag to false, and redirect 
               to the contact page template. */
        global $wp_query;
        $wp_query->set( 'is_404', false );
        include( get_stylesheet_directory().'/contact.php' );
        exit;
        }
    }

This will serve up your contact.php file for any requests for ?template=contact or /contact.

There’s probably a quicker way of doing it, but this works. Here’s a more thorough tutorial: Create Fake Pages in WordPress.

Leave a Comment