Using WordPress ‘locate_template()’ PHP function

The locate_template() WordPress PHP function retrieves the name of the highest priority template file that exists.

Usage

locate_template($template_names, $load = false, $load_once = true, $args = array())

Input:

$template = locate_template('single-post.php');

Output:

/path/to/your/theme/single-post.php

Parameters

  • $template_names (string|array) – Required. Template file(s) to search for, in order.
  • $load (bool) – Optional. If true, the template file will be loaded if it is found. Default: false.
  • $load_once (bool) – Optional. Whether to require_once or require. Has no effect if $load is false. Default: true.
  • $args (array) – Optional. Additional arguments passed to the template. Default: array().

More information

See WordPress Developer Resources: locate_template()

Examples

Load a specific template part based on the current page name

Explanation:
This example checks if a template part named ‘content-page_name.php’ exists, and if so, it loads that specific template part. Otherwise, it loads the regular content.

Code:

if (locate_template('content-' . $pageName . '.php') != '') {
    // Load the page-specific template
    get_template_part('content', $pageName);
} else {
    // Load the regular content
    the_content();
}

Locate and load a custom header

Explanation:
This example locates and loads a custom header file named ‘header-custom.php’ if it exists. If not, it loads the default ‘header.php’.

Code:

$custom_header = locate_template('header-custom.php', true);
if ($custom_header) {
    get_header('custom');
} else {
    get_header();
}

Load a template file from a plugin

Explanation:
This example locates and loads a template file named ‘custom-template.php’ from a plugin’s directory.

Code:

$plugin_path = plugin_dir_path(__FILE__);
$template = locate_template('custom-template.php', false, false, array('path' => $plugin_path));
if ($template) {
    load_template($template);
}

Load a specific sidebar based on post type

Explanation:
This example loads a specific sidebar file named ‘sidebar-post_type.php’ based on the current post type. If the specific sidebar file does not exist, it loads the default ‘sidebar.php’.

Code:

$post_type = get_post_type();
if (locate_template('sidebar-' . $post_type . '.php') != '') {
    get_sidebar($post_type);
} else {
    get_sidebar();
}

Load a fallback template if a specific template does not exist

Explanation:
This example tries to locate and load a specific template named ‘archive-special.php’. If it does not exist, it loads the default ‘archive.php’ file.

Code:

$special_archive = locate_template('archive-special.php', true);
if ($special_archive) {
    get_template_part('archive', 'special');
} else {
    get_template_part('archive');
}