函数文档

register_theme_directory()

💡 云策文档标注

概述

register_theme_directory() 函数用于注册一个包含主题的目录,允许 WordPress 从指定路径加载主题。它接受一个目录路径参数,并返回布尔值表示注册成功与否。

关键要点

  • 参数 $directory 是必需的字符串,可以是主题文件夹的完整文件系统路径,或相对于 WP_CONTENT_DIR 的路径。
  • 函数返回 true 表示成功注册包含主题的目录,false 表示目录不存在。
  • 内部处理包括检查目录是否存在,如果相对路径则尝试基于 WP_CONTENT_DIR 解析,并使用 untrailingslashit() 移除尾部斜杠。
  • 注册的目录会添加到全局数组 $wp_theme_directories 中,避免重复。

代码示例

// 注册插件子目录作为主题文件夹的示例
register_theme_directory( '/path/to/plugin/themes' );

注意事项

  • 确保目录存在且可访问,否则函数返回 false。
  • 路径可以是绝对路径或相对于 WP_CONTENT_DIR 的路径,函数会自动处理。
  • 使用 untrailingslashit() 确保目录路径格式一致,避免重复注册。

📄 原文内容

Registers a directory that contains themes.

Parameters

$directorystringrequired
Either the full filesystem path to a theme folder or a folder within WP_CONTENT_DIR.

Return

bool True if successfully registered a directory that contains themes, false if the directory does not exist.

Source

function register_theme_directory( $directory ) {
	global $wp_theme_directories;

	if ( ! file_exists( $directory ) ) {
		// Try prepending as the theme directory could be relative to the content directory.
		$directory = WP_CONTENT_DIR . '/' . $directory;
		// If this directory does not exist, return and do not register.
		if ( ! file_exists( $directory ) ) {
			return false;
		}
	}

	if ( ! is_array( $wp_theme_directories ) ) {
		$wp_theme_directories = array();
	}

	$untrailed = untrailingslashit( $directory );
	if ( ! empty( $untrailed ) && ! in_array( $untrailed, $wp_theme_directories, true ) ) {
		$wp_theme_directories[] = $untrailed;
	}

	return true;
}

Changelog

Version Description
2.9.0 Introduced.

User Contributed Notes