Include a file before current template file

template_redirect runs before template_include. You can demonstrate that with this:

add_filter( 'template_include', 'var_template_include', 1000 );
function var_template_include( $t ){
  echo __FUNCTION__;
}
// use template redirect to include file
add_action('template_redirect', 'ra_template_block');
function ra_template_block() {
  echo __FUNCTION__;  
}

Or you could just look at the source: http://core.trac.wordpress.org/browser/tags/3.5.2/wp-includes/template-loader.php

Since your code exits in template_redirect the global that get_current_template depends upon never gets set, and even if you didn’t exit it would be set too late.

You need the template path passed into template_include so if you just hook both filters to that hook and give them a priority so that the one always loads before the other this should work, at least insofar as setting and retrieving that global.

// current template file
add_filter( 'template_include', 'var_template_include', 1000 );
function var_template_include( $t ){
  var_dump($t);
  $GLOBALS['current_theme_template'] = basename($t);
  return $t;
}

// use template redirect to include file
add_action('template_include', 'ra_template_block', 1001);
function ra_template_block() {
//     include_once THEME_DIR.'/blockstop.php';
    var_dump(get_template_part(get_current_template()));      
//     include_once THEME_DIR.'/blocks.php';
    exit;
}

Of course, there is no real reason for two filters. One would do just as well.

Leave a Comment