Using WordPress ‘load_template()’ PHP function

The load_template() WordPress PHP function requires the template file with the WordPress environment and makes query variables available within the function.

Usage

To use the function, you would call it with the required file path, and optionally, whether to require_once or require, and additional arguments:

load_template($_template_file, $load_once, $args);

Parameters

  • $_template_file (string): Required. Path to the template file.
  • $load_once (bool): Optional. Whether to require_once or require. Default: true.
  • $args (array): Optional. Additional arguments passed to the template. Default: array().

More information

See WordPress Developer Resources: load_template()

Examples

Loading a template from a plugin, allowing theme and child theme to override

In this example, we check if the theme or child theme has overridden the template. If so, we load the overridden template. Otherwise, we load the template from the plugin’s ‘templates’ sub-directory.

if ($overridden_template = locate_template('some-template.php')) {
  load_template($overridden_template);
} else {
  load_template(dirname(__FILE__) . '/templates/some-template.php');
}

Passing variables to the template using load_template() and set_query_var()

In this example, we set a custom variable using set_query_var() and pass it to the template using load_template().

$template = locate_template('template.php');
if ($template) {
  set_query_var('my_variable', 'Hello Template File');
  load_template($template);
}

In the template.php file, you can access the variable like this:

echo $my_variable; // Output: "Hello Template File"

Using the $args parameter to pass variables to the template

In this example, we pass variables to the template using the $args parameter.

$template = locate_template('template.php');
if ($template) {
  $args = array('my_variable' => 'Hello Template File');
  load_template($template, true, $args);
}

In the template.php file, you can access the variable from the $args array:

echo $args['my_variable']; // Output: "Hello Template File"

Loading a template with a custom path

In this example, we load a template file with a custom path.

$template_file = '/path/to/your/custom-template.php';
load_template($template_file);

Loading a template without require_once

In this example, we load a template without using require_once.

$template_file = locate_template('template.php');
if ($template_file) {
  load_template($template_file, false);
}