locate_template()判断模版文件是否存在,存在则返回模版路径

目录

描述

Retrieve the name of the highest priority template file that exists, optionally loading that file.

Searches STYLESHEETPATH before TEMPLATEPATH, so themes which inherit from a parent can overload one file.

locate_template() 描述

用法

<?php locate_template$template_names$load$require_once ?>

locate_template() 用法

参数

$template_names

(array) (必填) Array of template files to search for, in priority order. (Requires file extension.)

默认值: None

$load

(boolean) (可选) If true, the template file will be loaded, if it is found.

默认值: false

$require_once

(boolean) (可选) If true, the template file will be loaded with the php require_once function. If false, the template file will be loaded with the php require function. This parameter has no effect if $load is false.

默认值: true

locate_template() 参数

返回值

(string) 

The template filename, if one is located, an empty string, if not.

locate_template() 返回值

示例

Load a specific template part based on the current pagename:

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */

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

locate_template() 示例

历史

添加于 版本: 2.7.0

locate_template() 历史

源文件

locate_template() 函数的代码位于 wp-includes/template.php.

/* ----------------------------------
 * wordpress之魂 © http://wphun.com
 * ---------------------------------- */
/**
 * Retrieve the name of the highest priority template file that exists.
 *
 * Searches in the STYLESHEETPATH before TEMPLATEPATH so that themes which
 * inherit from a parent theme can just overload one file.
 *
 * @since 2.7.0
 *
 * @param string|array $template_names Template file(s) to search for, in order.
 * @param bool         $load           If true the template file will be loaded if it is found.
 * @param bool         $require_once   Whether to require_once or require. Default true. Has no effect if $load is false.
 * @return string The template filename if one is located.
 */
function locate_template($template_names, $load = false, $require_once = true ) {
	$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;
		}
	}

	if ( $load && '' != $located )
		load_template( $located, $require_once );

	return $located;
}

locate_template() 源文件