locate_template() WordPress Function

The locate_template() function is used to search for a template file in the active theme's directory. If the template file is not found in the theme directory, the function will search for the template file in the parent theme's directory. If the template file is not found in either the theme or parent theme directory, the function will return an empty string.

locate_template( string|array $template_names, bool $load = false, bool $require_once = true, array $args = array() ) #

Retrieve 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.


Top ↑

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 value: false

$require_once

(bool)(Optional)Whether to require_once or require. Has no effect if $load is false.

Default value: true

$args

(array)(Optional) Additional arguments passed to the template.

Default value: array()


Top ↑

Return

(string) The template filename if one is located.


Top ↑

Source

File: wp-includes/template.php

function locate_template( $template_names, $load = false, $require_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, $require_once, $args );
	}

	return $located;
}


Top ↑

Changelog

Changelog
VersionDescription
5.5.0The $args parameter was added.
2.7.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.