wp_before_load_template
Fires before a template is included (output).
locate_template() is a low-level template inclusion function on which functions such as get_template_part(), get_header(), get_footer(), and others are based.
Together, the wp_before_load_template and wp_after_load_template events can, for example, measure the time required to include (generate) a template; see the example.
The hook was added through ticket #54541.
Usage
add_action( 'wp_before_load_template', 'wp_kama_before_load_template_action', 10, 3 );
/**
* Function for `wp_before_load_template` action-hook.
*
* @param string $_template_file The full path to the template file.
* @param bool $load_once Whether to require_once or require.
* @param array $args Additional arguments passed to the template.
*
* @return void
*/
function wp_kama_before_load_template_action( $_template_file, $load_once, $args ){
// action...
}
- $_template_file(string)
- Full path to the template file, for example
/home/site/www/wp-content/themes/mytheme/myfile.php. - $load_once(true|false)
truewhen the template was included withrequire_once.
falsewhen the template was included withrequire.- $args(array)
- Additional arguments passed to the included file.
Examples
#1 Measure the inclusion (generation) time of each template file
// Before including the template.
add_action( 'wp_before_load_template', 'wpkama_load_template_timer' );
// After including the template.
add_action( 'wp_after_load_template', 'wpkama_load_template_timer' );
// Output the collected data to the log file.
register_shutdown_function( 'wpkama_load_template_timer' );
function wpkama_load_template_timer( $file = null ){
static $files_start_times = [];
static $result = [];
if( doing_action( 'wp_before_load_template' ) ){
$files_start_times[ $file ] = microtime( true );
return;
}
if( doing_action( 'wp_after_load_template' ) ){
$result[ $file ][] = sprintf( '%.6f sec.', microtime( true ) - $files_start_times[ $file ] );
return;
}
// Shutdown.
error_log( print_r( $result, true ) );
}
The log file contains the following data. The ellipsis replaces the beginning of each full file path for brevity:
Array ( [.../templates/parts/header/svg.php] => Array ( [0] => 0.000394 sec. ) [.../templates/parts/header/header.php] => Array ( [0] => 0.010713 sec. ) [.../templates/event/archive/parts/event-card-full.php] => Array ( [0] => 0.000572 sec. [1] => 0.000530 sec. ) [.../templates/event/single/parts/upcoming-events.php] => Array ( [0] => 0.006188 sec. ) [.../templates/event/single/parts/schedule.php] => Array ( [0] => 0.000237 sec. ) [.../templates/parts/btn-to-top.php] => Array ( [0] => 0.000124 sec. ) [.../templates/parts/footer/footer.php] => Array ( [0] => 0.005845 sec. ) )
See also Measuring PHP script execution time and Debugging in WordPress.
Changelog
| Since 6.1.0 | Introduced. |
Where the hook is called
wp_before_load_template
wp-includes/template.php 811
do_action( 'wp_before_load_template', $_template_file, $load_once, $args );