wpseek.com
A WordPress-centric search engine for devs and theme authors



locate_template › WordPress Function

Since2.7.0
Deprecatedn/a
locate_template ( $template_names, $load = false, $require_once = true, $args = array() )
Parameters: (4)
  • (string|array) $template_names Template file(s) to search for, in order.
    Required: Yes
  • (bool) $load If true the template file will be loaded if it is found.
    Required: No
    Default: false
  • (bool) $require_once Whether to require_once or require. Has no effect if `$load` is false. Default true.
    Required: No
    Default: true
  • (array) $args Optional. Additional arguments passed to the template. Default empty array.
    Required: No
    Default: array()
Returns:
  • (string) The template filename if one is located.
Defined at:
Codex:
Change Log:
  • 5.5.0

Retrieve the name of the highest priority template file that exists.

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.


Source

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 ) {
		/**
		 * Fires before a located template is loaded.
		 *
		 * @since 6.1.0
		 *
		 * @param string       $located        The template filename.
		 * @param string|array $template_names Template file(s) to search for, in order.
		 * @param bool         $require_once   Whether to require_once or require.
		 * @param array        $args           Additional arguments passed to the template.
		 */
		do_action( 'wp_before_load_template', $located, $template_names, $require_once, $args );

		load_template( $located, $require_once, $args );

		/**
		 * Fires after a located template is loaded.
		 *
		 * @since 6.1.0
		 *
		 * @param string       $located        The template filename.
		 * @param string|array $template_names Template file(s) to search for, in order.
		 * @param bool         $require_once   Whether to require_once or require.
		 * @param array        $args           Additional arguments passed to the template.
		 */
		do_action( 'wp_after_load_template', $located, $template_names, $require_once, $args );
	}

	return $located;
}