For example:
site.com/contact
(or site.com/?page=contact
if not using permalinks)
when someone goes to that page I want to load a theme template, like page-contact.php
But I don’t want to create a page in the dashboard for this work. How can I do this internally, within functions.php ?
I know it’s possible because that bbpress plugin does it somehow for the /users/ pages, which are not standard wordpress 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.