函数文档

wp_get_active_and_valid_themes()

💡 云策文档标注

概述

wp_get_active_and_valid_themes() 函数用于检索当前活动且有效的主题数组,返回主题目录的绝对路径。在 WordPress 升级或安装过程中,该函数不会返回任何主题。

关键要点

  • 函数返回一个包含活动主题和有效主题目录绝对路径的数组。
  • 在 WordPress 安装模式(wp_installing() 为 true)且当前页面不是 wp-activate.php 时,返回空数组。
  • 如果使用子主题,数组会包含子主题目录($wp_stylesheet_path)和父主题目录($wp_template_path)。
  • 在恢复模式(wp_is_recovery_mode())下,会通过 wp_skip_paused_themes() 过滤掉暂停的主题,若无有效主题则禁用主题加载。

代码示例

function wp_get_active_and_valid_themes() {
	global $pagenow, $wp_stylesheet_path, $wp_template_path;

	$themes = array();

	if ( wp_installing() && 'wp-activate.php' !== $pagenow ) {
		return $themes;
	}

	if ( is_child_theme() ) {
		$themes[] = $wp_stylesheet_path;
	}

	$themes[] = $wp_template_path;

	/*
	 * Remove themes from the list of active themes when we're on an endpoint
	 * that should be protected against WSODs and the theme is paused.
	 */
	if ( wp_is_recovery_mode() ) {
		$themes = wp_skip_paused_themes( $themes );

		// If no active and valid themes exist, skip loading themes.
		if ( empty( $themes ) ) {
			add_filter( 'wp_using_themes', '__return_false' );
		}
	}

	return $themes;
}

注意事项

  • 该函数自 WordPress 5.1.0 版本引入。
  • 相关函数包括 wp_is_recovery_mode()、wp_skip_paused_themes()、wp_installing()、is_child_theme() 和 add_filter()。
  • 主要用于内部调用,如 _register_theme_block_patterns() 函数。

📄 原文内容

Retrieves an array of active and valid themes.

Description

While upgrading or installing WordPress, no themes are returned.

Return

string[] Array of absolute paths to theme directories.

Source

function wp_get_active_and_valid_themes() {
	global $pagenow, $wp_stylesheet_path, $wp_template_path;

	$themes = array();

	if ( wp_installing() && 'wp-activate.php' !== $pagenow ) {
		return $themes;
	}

	if ( is_child_theme() ) {
		$themes[] = $wp_stylesheet_path;
	}

	$themes[] = $wp_template_path;

	/*
	 * Remove themes from the list of active themes when we're on an endpoint
	 * that should be protected against WSODs and the theme is paused.
	 */
	if ( wp_is_recovery_mode() ) {
		$themes = wp_skip_paused_themes( $themes );

		// If no active and valid themes exist, skip loading themes.
		if ( empty( $themes ) ) {
			add_filter( 'wp_using_themes', '__return_false' );
		}
	}

	return $themes;
}

Changelog

Version Description
5.1.0 Introduced.