locate_template( string|array $template_names, bool $load = false, bool $load_once = true, array $args = array() ): string
Retrieves the name of the highest priority template file that exists.
Description
Searches in the STYLESHEETPATH before TEMPLATEPATH and wp-includes/theme-compat so that themes which inherit from a parent theme can just overload one file.
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()
Return
string The template filename if one is located.
Source
File: wp-includes/template.php
.
View all references
function locate_template( $template_names, $load = false, $load_once = true, $args = array() ) {
$located = '';
foreach ( (array) $template_names as $template_name ) {
if ( ! $template_name ) {
continue;
}
if ( file_exists( STYLESHEETPATH . '/' . $template_name ) ) {
$located = STYLESHEETPATH . '/' . $template_name;
break;
} elseif ( file_exists( TEMPLATEPATH . '/' . $template_name ) ) {
$located = TEMPLATEPATH . '/' . $template_name;
break;
} elseif ( file_exists( ABSPATH . WPINC . '/theme-compat/' . $template_name ) ) {
$located = ABSPATH . WPINC . '/theme-compat/' . $template_name;
break;
}
}
if ( $load && '' !== $located ) {
load_template( $located, $load_once, $args );
}
return $located;
}
Changelog
Version | Description |
---|---|
5.5.0 | The $args parameter was added. |
2.7.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.
Note that
locate_template()
does not prevent directory traversal attacks, so if you’re passing a user-provided template name to the function, be sure to verify that it’s from one of the three appropriate locations (active theme directory, parent theme directory, or /wp-includes/theme-compat/ directory).Example:
Example
Load a specific template part based on the current pagename.