wp_get_themes()WP 3.4.0

Получает данные всех тем (шаблонов) из папки "themes". Данные отдаются в виде массива объектов: каждый объект набор данных темы.

Скорость работы функции напрямую зависит от того, сколько у вас тем в папке "themes". Поэтому в целях производительности ограничитесь функцией wp_get_theme(), если это возможно.

Если нужно просто получить названия всех тем (названия директорий тем), можно воспользоваться функцией search_theme_directories().

Аналогичная функция для получения данных плагинов: get_plugins()

Работает на основе: search_theme_directories()

Хуков нет.

Возвращает

WP_Theme[].

Использование

wp_get_themes( $args );

Параметры $args

$args(массив)

Массив аргументов по которым будет получен результат. Может принимать следующие аргументы:

  • errors - Может быть:

    • "true" - чтобы вернуть темы с ошибками.
    • "false" - чтобы вернуть темы без ошибок.
    • "null" - чтобы вернуть все темы.

    по умолчанию false

  • allowed (мультисайты) - Может быть:

    • "true" - чтобы вернуть только доступные для сайта темы.
    • "false" - чтобы вернуть недоступные для сайта темы.
    • "site" - чтобы вернуть темы доступные для сайтов сети.
    • "network" - чтобы вернуть темы доступные для самой сети.
    • "null" - вернет все темы.

    по умолчанию null

  • blog_id (мультисайты) - ID блога темы для которого доступны. По умолчанию 0 (означает - текущий блог).

По умолчанию: array( 'errors' => false , 'allowed' => null, 'blog_id' => 0 )

Примеры

0

#1 Получим данные всех существующих тем (шаблонов)

$themes = wp_get_themes();

$themes будет содержать следующий массив:

Array
(
	[twentyfourteen] => WP_Theme Object
		(
			[theme_root:WP_Theme:private] => C:/sites/example.com/www/wp-content/themes
			[headers:WP_Theme:private] => Array
				(
					[Name] => Twenty Fourteen
					[ThemeURI] => http://wordpress.org/themes/twentyfourteen
					[Description] => In 2014, our default theme lets you create a responsive magazine website with a sleek, modern design. Feature your favorite homepage content in either a grid or a slider. Use the three widget areas to customize your website, and change your content's layout with a full-width page template and a contributor page to show off your authors. Creating a magazine website with WordPress has never been easier.
					[Author] => the WordPress team
					[AuthorURI] => http://wordpress.org/
					[Version] => 1.0
					[Template] => 
					[Status] => 
					[Tags] => black, green, white, light, dark, two-columns, three-columns, left-sidebar, right-sidebar, fixed-layout, responsive-layout, custom-background, custom-header, custom-menu, editor-style, featured-images, flexible-header, full-width-template, microformats, post-formats, rtl-language-support, sticky-post, theme-options, translation-ready, accessibility-ready
					[TextDomain] => twentyfourteen
					[DomainPath] => 
				)

			[headers_sanitized:WP_Theme:private] => 
			[name_translated:WP_Theme:private] => 
			[errors:WP_Theme:private] => 
			[stylesheet:WP_Theme:private] => twentyfourteen
			[template:WP_Theme:private] => twentyfourteen
			[parent:WP_Theme:private] => 
			[theme_root_uri:WP_Theme:private] => 
			[textdomain_loaded:WP_Theme:private] => 
			[cache_hash:WP_Theme:private] => c997aa5b2bccf71942eebe3c280effb1
		)

	[twentythirteen] => WP_Theme Object
		(
		...
		)

	[twentytwelve] => WP_Theme Object
		(
		...
		)
)

Заметки

  • Global. Массив. $wp_theme_directories

Список изменений

С версии 3.4.0 Введена.

Код wp_get_themes() WP 6.5.2

function wp_get_themes( $args = array() ) {
	global $wp_theme_directories;

	$defaults = array(
		'errors'  => false,
		'allowed' => null,
		'blog_id' => 0,
	);
	$args     = wp_parse_args( $args, $defaults );

	$theme_directories = search_theme_directories();

	if ( is_array( $wp_theme_directories ) && count( $wp_theme_directories ) > 1 ) {
		/*
		 * Make sure the active theme wins out, in case search_theme_directories() picks the wrong
		 * one in the case of a conflict. (Normally, last registered theme root wins.)
		 */
		$current_theme = get_stylesheet();
		if ( isset( $theme_directories[ $current_theme ] ) ) {
			$root_of_current_theme = get_raw_theme_root( $current_theme );
			if ( ! in_array( $root_of_current_theme, $wp_theme_directories, true ) ) {
				$root_of_current_theme = WP_CONTENT_DIR . $root_of_current_theme;
			}
			$theme_directories[ $current_theme ]['theme_root'] = $root_of_current_theme;
		}
	}

	if ( empty( $theme_directories ) ) {
		return array();
	}

	if ( is_multisite() && null !== $args['allowed'] ) {
		$allowed = $args['allowed'];
		if ( 'network' === $allowed ) {
			$theme_directories = array_intersect_key( $theme_directories, WP_Theme::get_allowed_on_network() );
		} elseif ( 'site' === $allowed ) {
			$theme_directories = array_intersect_key( $theme_directories, WP_Theme::get_allowed_on_site( $args['blog_id'] ) );
		} elseif ( $allowed ) {
			$theme_directories = array_intersect_key( $theme_directories, WP_Theme::get_allowed( $args['blog_id'] ) );
		} else {
			$theme_directories = array_diff_key( $theme_directories, WP_Theme::get_allowed( $args['blog_id'] ) );
		}
	}

	$themes         = array();
	static $_themes = array();

	foreach ( $theme_directories as $theme => $theme_root ) {
		if ( isset( $_themes[ $theme_root['theme_root'] . '/' . $theme ] ) ) {
			$themes[ $theme ] = $_themes[ $theme_root['theme_root'] . '/' . $theme ];
		} else {
			$themes[ $theme ] = new WP_Theme( $theme, $theme_root['theme_root'] );

			$_themes[ $theme_root['theme_root'] . '/' . $theme ] = $themes[ $theme ];
		}
	}

	if ( null !== $args['errors'] ) {
		foreach ( $themes as $theme => $wp_theme ) {
			if ( $wp_theme->errors() != $args['errors'] ) {
				unset( $themes[ $theme ] );
			}
		}
	}

	return $themes;
}