函数文档

get_parent_theme_file_path()

💡 云策文档标注

概述

get_parent_theme_file_path() 函数用于获取父主题中指定文件的路径。它接受一个可选文件名参数,返回文件在父主题目录中的完整路径。

关键要点

  • 函数返回父主题中文件的路径,常用于子主题开发中引用父主题资源。
  • 参数 $file 为可选字符串,指定要查找的文件;若为空,则返回父主题目录路径。
  • 内部使用 get_template_directory() 构建路径,并通过 parent_theme_file_path 过滤器允许修改路径。
  • 适用于安全地包含或要求父主题中的 PHP 文件,如 functions.php 中的引用。

代码示例

require get_parent_theme_file_path( '/inc/your-file-name.php' );

注意事项

  • 确保文件路径正确,避免因路径错误导致包含失败。
  • 使用此函数可提高代码可移植性,特别是在子主题环境中。

📄 原文内容

Retrieves the path of a file in the parent theme.

Parameters

$filestringoptional
File to return the path for in the template directory.

Return

string The path of the file.

Source

function get_parent_theme_file_path( $file = '' ) {
	$file = ltrim( $file, '/' );

	if ( empty( $file ) ) {
		$path = get_template_directory();
	} else {
		$path = get_template_directory() . '/' . $file;
	}

	/**
	 * Filters the path to a file in the parent theme.
	 *
	 * @since 4.7.0
	 *
	 * @param string $path The file path.
	 * @param string $file The requested file to search for.
	 */
	return apply_filters( 'parent_theme_file_path', $path, $file );
}

Hooks

apply_filters( ‘parent_theme_file_path’, string $path, string $file )

Filters the path to a file in the parent theme.

Changelog

Version Description
4.7.0 Introduced.

User Contributed Notes