wp_get_global_stylesheet()WP 5.9.0

Получает готовый CSS-код из смерженных данных theme.json, вариаций стилей и кастомных настроек пользователя.

Функция собирает пресеты (палитры, масштабы, границы и т. д.), переменные и другие объявления из theme.json, учитывает кастомные правки в панели «Глобальные стили», а затем превращает их в CSS строку.

Результат кэшируется в object-cache (группа theme_json) и не кэшируется при включённом dev-режиме theme.

По умолчанию глобальные переменные подключатся через wp_enqueue_global_styles_css_custom_properties() на хуке:

// add wp_get_global_stylesheet( [ 'variables' ] )
add_action( 'enqueue_block_editor_assets', 'wp_enqueue_global_styles_css_custom_properties' );

Используйте wp_clean_theme_json_cache() для сброса кэша, если нужно немедленно получить обновлённые стили.

Работает на основе: WP_Theme_JSON::get_stylesheet(), wp_theme_has_theme_json()

Хуков нет.

Возвращает

Строку. CSS-строку глобальных стилей темы.

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

wp_get_global_stylesheet( $types );
$types(array)

Массив сегментов, которые нужно включить в вывод. Передавая нужные сегменты, можно сократить объём стилей, если требуется только часть.

Возможные сегменты:

  • variables — только CSS-переменные (Custom Properties) для пресетов и пользовательских значений.
  • styles — только содержимое секции styles в theme.json.
  • presets — только CSS-классы для пресетов.
  • base-layout-styles — только базовые стили раскладки.
  • custom-css — только пользовательский CSS.

Если указать пустой массив (по-умолчанию), то будут получены следующие сегменты:

  • Для тем без theme.json: variables, presets, base-layout-styles.
  • Для тем с theme.json: variables, presets, styles.

Допустимые значения совпадают с первым аргументом метода WP_Theme_JSON::get_stylesheet().

По умолчанию: []

Примеры

0

#1 Демо

Результат зависит от параметров theme.json и настроект стилей.

variables:

echo wp_get_global_stylesheet( [ 'variables' ] );
:root {
	--wp--preset--aspect-ratio--square: 1;
	--wp--preset--aspect-ratio--4-3: 4/3;
	--wp--preset--color--white: #ffffff;
	--wp--preset--color--light-green-cyan: #7bdcb5;
	--wp--preset--color--vivid-green-cyan: #00d084;
	--wp--preset--font-size--small: 13px;
	--wp--preset--font-size--medium: 20px;
	--wp--preset--spacing--20: 0.44rem;
	--wp--preset--spacing--30: 0.67rem;
	//...
}

presets:

echo wp_get_global_stylesheet( [ 'presets' ] );
.has-black-color {
	color: var(--wp--preset--color--black) !important;
}

.has-cyan-bluish-gray-color {
	color: var(--wp--preset--color--cyan-bluish-gray) !important;
}

//...

styles:

echo wp_get_global_stylesheet( [ 'styles' ] );
:root {
	--wp--style--global--content-size: var(--layout-content-width);
	--wp--style--global--wide-size: var(--layout-wide-content-width);
}

:where(body) {
	margin: 0;
}

:root :where(.is-layout-flex) {
	gap: var(--space-lg);
}

:root :where(.is-layout-grid) {
	gap: var(--space-lg);
}

.wp-site-blocks {
	padding-top: var(--wp--style--root--padding-top);
	padding-bottom: var(--wp--style--root--padding-bottom);
}

.is-layout-flow > .alignleft {
	float: left;
	margin-inline-start: 0;
	margin-inline-end: 2em;
}

.is-layout-flow > .alignright {
	float: right;
	margin-inline-start: 2em;
	margin-inline-end: 0;
}

.is-layout-flow > .aligncenter {
	margin-left: auto !important;
	margin-right: auto !important;
}

.is-layout-constrained > .alignleft {
	float: left;
	margin-inline-start: 0;
	margin-inline-end: 2em;
}

.is-layout-constrained > .alignright {
	float: right;
	margin-inline-start: 2em;
	margin-inline-end: 0;
}

.is-layout-constrained > .aligncenter {
	margin-left: auto !important;
	margin-right: auto !important;
}

.is-layout-constrained > :where(:not(.alignleft):not(.alignright):not(.alignfull)) {
	max-width: var(--wp--style--global--content-size);
	margin-left: auto !important;
	margin-right: auto !important;
}

.is-layout-constrained > .alignwide {
	max-width: var(--wp--style--global--wide-size);
}

body .is-layout-flex {
	display: flex;
}

.is-layout-flex {
	flex-wrap: wrap;
	align-items: center;
}

.is-layout-flex > :is(*, div) {
	margin: 0;
}

body .is-layout-grid {
	display: grid;
}

.is-layout-grid > :is(*, div) {
	margin: 0;
}

body {
	background-color: var(--color-surface-primary);
	color: var(--color-content-primary);
	font-family: var(--font-family-basic);
	font-size: var(--font-size-lg);
	font-weight: 400;
	letter-spacing: var(--letter-spacing-normal);
	line-height: var(--line-height-normal);
	--wp--style--root--padding-top: 0px;
	--wp--style--root--padding-right: var(--space-2xl);
	--wp--style--root--padding-bottom: 0px;
	--wp--style--root--padding-left: var(--space-2xl);
}

a:where(:not(.wp-element-button)) {
	color: currentColor;
	text-decoration: underline;
}

:root :where(a:where(:not(.wp-element-button)):hover) {
	text-decoration: none;
}

h1, h2, h3, h4, h5, h6 {
	font-family: var(--font-family-headers);
	font-weight: 500;
	letter-spacing: var(--letter-spacing-normal);
	line-height: var(--line-height-tight);
}

h1 {
	font-size: var(--font-size-7xl);
}

:root :where(.wp-element-button, .wp-block-button__link) {
	background-color: #32373c;
	border-width: 0;
	color: #fff;
	font-family: inherit;
	font-size: inherit;
	line-height: inherit;
	padding: calc(0.667em + 2px) calc(1.333em + 2px);
	text-decoration: none;
}

// ...

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

С версии 5.9.0 Введена.
С версии 6.1.0 Added 'base-layout-styles' support.
С версии 6.6.0 Resolves relative paths in theme.json styles to theme absolute paths.
С версии 7.0.0 Deprecated 'base-layout-styles' type; classic themes now receive full styles with layout-specific alignment rules skipped via base_layout_styles option.

Код wp_get_global_stylesheet() WP 7.0

function wp_get_global_stylesheet( $types = array() ) {
	/*
	 * Ignore cache when the development mode is set to 'theme', so it doesn't interfere with the theme
	 * developer's workflow.
	 */
	$can_use_cached = empty( $types ) && ! wp_is_development_mode( 'theme' );

	/*
	 * By using the 'theme_json' group, this data is marked to be non-persistent across requests.
	 * @see `wp_cache_add_non_persistent_groups()`.
	 *
	 * The rationale for this is to make sure derived data from theme.json
	 * is always fresh from the potential modifications done via hooks
	 * that can use dynamic data (modify the stylesheet depending on some option,
	 * settings depending on user permissions, etc.).
	 * See some of the existing hooks to modify theme.json behavior:
	 * @see https://make.wordpress.org/core/2022/10/10/filters-for-theme-json-data/
	 *
	 * A different alternative considered was to invalidate the cache upon certain
	 * events such as options add/update/delete, user meta, etc.
	 * It was judged not enough, hence this approach.
	 * @see https://github.com/WordPress/gutenberg/pull/45372
	 */
	$cache_group = 'theme_json';
	$cache_key   = 'wp_get_global_stylesheet';
	if ( $can_use_cached ) {
		$cached = wp_cache_get( $cache_key, $cache_group );
		if ( $cached ) {
			return $cached;
		}
	}

	$tree = WP_Theme_JSON_Resolver::resolve_theme_file_uris( WP_Theme_JSON_Resolver::get_merged_data() );

	if ( empty( $types ) ) {
		$types = array( 'variables', 'styles', 'presets' );
	}

	/*
	 * Enable base layout styles only mode for classic themes without theme.json.
	 * This skips alignment styles that target .wp-site-blocks which is only used by block themes.
	 */
	$options = array();
	if ( ! wp_is_block_theme() && ! wp_theme_has_theme_json() ) {
		$options['base_layout_styles'] = true;
	}

	/*
	 * If variables are part of the stylesheet, then add them.
	 * This is so themes without a theme.json still work as before 5.9:
	 * they can override the default presets.
	 * See https://core.trac.wordpress.org/ticket/54782
	 */
	$styles_variables = '';
	if ( in_array( 'variables', $types, true ) ) {
		/*
		 * Only use the default, theme, and custom origins. Why?
		 * Because styles for `blocks` origin are added at a later phase
		 * (i.e. in the render cycle). Here, only the ones in use are rendered.
		 * @see wp_add_global_styles_for_blocks
		 */
		$origins          = array( 'default', 'theme', 'custom' );
		$styles_variables = $tree->get_stylesheet( array( 'variables' ), $origins, $options );
		$types            = array_diff( $types, array( 'variables' ) );
	}

	/*
	 * For the remaining types (presets, styles), we do consider origins:
	 *
	 * - themes without theme.json: only the classes for the presets defined by core
	 * - themes with theme.json: the presets and styles classes, both from core and the theme
	 */
	$styles_rest = '';
	if ( ! empty( $types ) ) {
		/*
		 * Only use the default, theme, and custom origins. Why?
		 * Because styles for `blocks` origin are added at a later phase
		 * (i.e. in the render cycle). Here, only the ones in use are rendered.
		 * @see wp_add_global_styles_for_blocks
		 */
		$origins     = array( 'default', 'theme', 'custom' );
		$styles_rest = $tree->get_stylesheet( $types, $origins, $options );
	}

	$stylesheet = $styles_variables . $styles_rest;
	if ( $can_use_cached ) {
		wp_cache_set( $cache_key, $stylesheet, $cache_group );
	}

	return $stylesheet;
}