描述:
判断模版文件是否存在,存在则返回模版路径
用法:
<?php locate_template( $template_names, $load, $require_once ) ?>
参数:
$template_names
(array) (必填) 按优先级顺序搜索的模板文件名称组成的数组。(需要文件扩展名。)
默认值: None
$load
(boolean) (可选) 如果为true,将加载模板文件(如果找到)。
默认值: false
$require_once
(boolean) (可选) 如果为true,模板文件将加载 require_once函数。如果为false,则模板文件将与 require函数一起加载。如果$load为false,则此参数无效。
默认值: true
示例:
if (locate_template('content-' . $pageName . '.php') != '') {
// yep, load the page template
get_template_part('content', $pageName);
} else {
// nope, load the content
the_content();
}
源文件:
/**
* 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;
}