[wp-hackers] Superseding WordPress templates and globals

John Blackbourn johnbillion+wp at gmail.com
Mon Aug 6 19:25:59 UTC 2012

On 6 August 2012 19:14, William P. Davis <will.davis at gmail.com> wrote:
> So, I'm trying to clean up our WordPress template, which has quite a few
> custom pages (as in page-my-page.php). I figured the best thing to do would
> be to throw all those pages into a subfolder in my theme called pages and
> then use template_redirect to check to see if a custom page template exists
> in that folder.
> When I do that, though, I lose access to all the globals such as $post and
> any plugins that use classes. So, is there a better way to include the new
> template or add a new place for WordPress to find a template than using
> template_redirect? Is there a huge negative performance impact if I do
> something like loop through all the globals and set it as a global inside
> the function?

Rather than the template_redirect hook you'll probably want the
template_include filter. Example:

add_filter( 'template_include', 'my_template_include' );
function my_template_include( $template ) {
  if ( something_or_other() )
    return locate_template( 'pages/foo.php' );
    return $template;

This filters the name of the template which WordPress' template loader
loads. Using this method you'll still have access to all the globals
which WordPress loads when it loads a template.


More information about the wp-hackers mailing list