If you did want to use include_once
in the template files, you could preload them by buffering the output of template-loader.php
early. This way the files would be included the first time and the template would output as standard.
The advantage is you can keep track of what is included directly in the templates themselves rather than having to keep a separate index to match actions and templates.
add_action('init','preload_template_includes');
function preload_template_includes() {
ob_start();
require_once( ABSPATH . WPINC . '/template-loader.php' );
ob_end_clean();
}
Note: not sure that init
hook is the earliest but is usually sufficient... setup_theme
or after_setup_theme
are other possibilities.
EDIT If you are concerned about performance issues loading the template twice, you can add some extra logic at the top of the template where the includes are run to handle the conditional loading of the template itself OR it's includes. eg.
// list of relevant includes files
$includes = array(
dirname(__FILE__).'/template-functions1.php',
dirname(__FILE__).'/template-functions2.php'
);
$included = get_included_files(); $doneincludes = false;
foreach ($includes as $include) {
if (!in_array($include,$included)) {include($include); $doneincludes = true;}
}
if ($doneincludes) {return;}
...the Template itself...
EDIT2 Sorry I missed you were wanting to do this in a plugin, the above is more an approach for theme development... Try something like this:
add_filter('template_include','myplugin_template_preload_check');
function myplugin_template_preload_check($template) {
global $pluginpreload;
// so is run only the first time
if ( (isset($pluginpreload)) && ($pluginpreload) ) {return;}
$templatefile = basename($template);
$templatefunctions = MYPLUGINDIR.'/template-functions/'.$templatefile;
if (file_exists($templatefunctions)) {include($templatefunctions);}
$pluginpreload = true;
// do not actually process the template
return false;
}
add_action('init','myplugin_preload_templates');
function myplugin_preload_templates() {
ob_start();
require_once( ABSPATH . WPINC . '/template-loader.php' );
ob_end_clean();
}
This way you could match your included functions in the plugin to the template used by matching the template name.