locate_template()

最后更新于:2021-11-27 14:24:07

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.

参数

$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()

响应

(string) The template filename if one is located.

源文件

文件: gc-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 . GCINC . '/theme-compat/' . $template_name ) ) {
			$located = ABSPATH . GCINC . '/theme-compat/' . $template_name;
			break;
		}
	}

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

	return $located;
}
$template = locate_template( $template_filename_from_unsanitized_user_input );

// Only allow templates that are in the active theme directory, parent theme
// directory, or the /gc-includes/theme-compat/ directory (prevent directory 
// traversal attacks).
$template_in_theme_or_parent_theme_or_compat = (
	// Template is in current theme folder.
	0 === strpos( realpath( $template ), realpath( STYLESHEETPATH ) ) ||
	// Template is in current or parent theme folder.
	0 === strpos( realpath( $template ), realpath( TEMPLATEPATH ) ) ||
	// Template is in theme-compat folder.
	0 === strpos( realpath( $template ), realpath( ABSPATH . GCINC . '/theme-compat/' ) )
);

if ( $template_in_theme_or_parent_theme_or_compat ) {
	require_once( $template );
}