Skip to content

Instantly share code, notes, and snippets.

@imvaskii
Last active November 17, 2016 00:44
Show Gist options
  • Save imvaskii/ce079e8dc791d3d7ed5e07a06e59c5c2 to your computer and use it in GitHub Desktop.
Save imvaskii/ce079e8dc791d3d7ed5e07a06e59c5c2 to your computer and use it in GitHub Desktop.
Custom template router for WordPress.
<?php
add_action('template_redirect', 'twr_custom_template_router', 1);
if( ! function_exists( 'twr_custom_template_router' ) ) {
/**
* Routes predefined list of pages to custom template_redirect
*/
function twr_custom_template_router() {
$custom_templates_bucket = array( 'schoolsguide', 'school' );
$request_uri = $_SERVER['REQUEST_URI'];
$url_segments = explode( '/', $request_uri );
foreach( $custom_templates_bucket as $custom_template ) {
$index = array_search( $custom_template, $url_segments );
if( $index ) {
$template_name = $url_segments[ $index ];
$template_path = get_stylesheet_directory() . '/custom-templates/' . $template_name . '.php';
twr_include_wordpress_template( $template_path );
}
}
}
}
if( ! function_exists( 'twr_include_wordpress_template' ) ) {
/**
* Renders template file
*/
function twr_include_wordpress_template( $template_path ) {
if( ! file_exists( $template_path ) )
return;
global $wp_query;
if ( $wp_query->is_404 )
$wp_query->is_404 = false;
header("HTTP/1.1 200 OK");
include( $template_path );
exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment