_wp_is_template_path_allowed() │ WP 7.1.2

Determines whether a template found by locate_template() may be loaded.

Internal function — this function is designed to be used by the kernel itself. It is not recommended to use this function in your code.

No Hooks.

Returns

bool. Whether the template may be loaded.

Usage

_wp_is_template_path_allowed( $path );
$path(string) (required)
Path to an existing template file.

Notes

Global. String. $wp_stylesheet_path Path to current theme's stylesheet directory.
Global. String. $wp_template_path Path to current theme's template directory.

Changelog

Since 7.1.2 Introduced.

_wp_is_template_path_allowed() code WP 7.1.2

function _wp_is_template_path_allowed( $path ) {
	global $wp_stylesheet_path, $wp_template_path;

	// A file path that exists and does not contain `..` is allowed.
	if ( 0 === preg_match( '#(?:^|/)\.\.[. ]*(?:/|$)#', wp_normalize_path( $path ) ) ) {
		return true;
	}

	// Resolve the true location of the requested file for later comparison.
	$real_path = realpath( $path );

	if ( false === $real_path ) {
		return false;
	}

	$real_path = trailingslashit( wp_normalize_path( $real_path ) );

	$directories = array(
		$wp_stylesheet_path,
		$wp_template_path,
		ABSPATH . WPINC . '/theme-compat',
	);

	// If a theme is in a subdirectory, accept templates from its direct parent directory.
	if ( str_contains( get_stylesheet(), '/' ) ) {
		$directories[] = dirname( $wp_stylesheet_path );
	}

	// If a parent theme is in a subdirectory, accept templates from its direct parent directory.
	if ( str_contains( get_template(), '/' ) ) {
		$directories[] = dirname( $wp_template_path );
	}

	foreach ( $directories as $directory ) {
		$real_directory = realpath( $directory );

		if ( false === $real_directory ) {
			continue;
		}

		// The true location of the requested file must be inside one of the allowed directories.
		if ( str_starts_with( $real_path, trailingslashit( wp_normalize_path( $real_directory ) ) ) ) {
			return true;
		}
	}

	return false;
}