WP_Theme_JSON::get_styles_for_blockpublicWP 6.1.0

Gets the CSS rules for a particular block from theme.json.

Method of the class: WP_Theme_JSON{}

No Hooks.

Returns

String. Styles for the block.

Usage

$WP_Theme_JSON = new WP_Theme_JSON();
$WP_Theme_JSON->get_styles_for_block( $block_metadata );
$block_metadata(array) (required)
Metadata about the block to get styles for.

Changelog

Since 6.1.0 Introduced.
Since 6.6.0 Setting a min-height of HTML when root styles have a background gradient or image. Updated general global styles specificity to 0-1-0. Fixed custom CSS output in block style variations.

WP_Theme_JSON::get_styles_for_block() code WP 7.1

public function get_styles_for_block( $block_metadata ) {
	$node                     = _wp_array_get( $this->theme_json, $block_metadata['path'], array() );
	$use_root_padding         = isset( $this->theme_json['settings']['useRootPaddingAwareAlignments'] ) && true === $this->theme_json['settings']['useRootPaddingAwareAlignments'];
	$selector                 = $block_metadata['selector'];
	$settings                 = $this->theme_json['settings'] ?? array();
	$feature_declarations     = static::get_feature_declarations_for_node( $block_metadata, $node );
	$is_root_selector         = static::ROOT_BLOCK_SELECTOR === $selector;
	$media_query              = $block_metadata['media_query'] ?? null;
	$responsive_media_queries = static::get_viewport_media_queries( $settings['viewport'] ?? null );

	// Update text indent selector for paragraph blocks based on the textIndent setting.
	$block_name           = $block_metadata['name'] ?? null;
	$feature_declarations = static::update_paragraph_text_indent_selector( $feature_declarations, $settings, $block_name );
	$block_elements       = $block_metadata['elements'] ?? array();

	// Update button width declarations for percentage values to use calc() with block gap.
	$feature_declarations = static::update_button_width_declarations( $feature_declarations, $settings );

	// If there are style variations, generate the declarations for them, including any feature selectors the block may have.
	$style_variation_declarations          = array();
	$style_variation_custom_css            = array();
	$style_variation_responsive_css        = array();
	$style_variation_responsive_pseudo_css = array();
	$style_variation_layout_metadata       = array();
	if ( ! $media_query && ! empty( $block_metadata['variations'] ) ) {
		foreach ( $block_metadata['variations'] as $style_variation ) {
			$style_variation_node = _wp_array_get( $this->theme_json, $style_variation['path'], array() );

			// Generate any feature/subfeature style declarations for the current style variation.
			$variation_declarations = static::get_feature_declarations_for_node( $block_metadata, $style_variation_node );

			// Update text indent selector for paragraph blocks based on the textIndent setting.
			$variation_declarations = static::update_paragraph_text_indent_selector( $variation_declarations, $settings, $block_name );

			// Update button width declarations for percentage values to use calc() with block gap.
			$variation_declarations = static::update_button_width_declarations( $variation_declarations, $settings );

			// Combine selectors with style variation's selector and add to overall style variation declarations.
			foreach ( $variation_declarations as $current_selector => $new_declarations ) {
				$combined_selectors = static::get_block_style_variation_feature_selector( $style_variation, $current_selector );

				// Add the new declarations to the overall results under the modified selector.
				$style_variation_declarations[ $combined_selectors ] = $new_declarations;
			}

			// Compute declarations for remaining styles not covered by feature level selectors.
			$style_variation_declarations[ $style_variation['selector'] ] = static::compute_style_properties( $style_variation_node, $settings, null, $this->theme_json );

			// Process pseudo-selectors for this variation (e.g., :hover, :focus)
			if ( isset( $block_metadata['name'] ) ) {
				$block_name = $block_metadata['name'];
			} elseif ( in_array( 'blocks', $block_metadata['path'], true ) && count( $block_metadata['path'] ) >= 3 ) {
				$block_name = static::get_block_name_from_metadata_path( $block_metadata );
			} else {
				$block_name = null;
			}
			$variation_pseudo_declarations = $this->process_pseudo_selectors( $style_variation_node, $style_variation['selector'], $settings, $block_name, $block_metadata, $style_variation );
			$style_variation_declarations  = array_merge( $style_variation_declarations, $variation_pseudo_declarations );

			// Store custom CSS for the style variation.
			if ( isset( $style_variation_node['css'] ) ) {
				$style_variation_custom_css[ $style_variation['selector'] ] = $this->process_blocks_custom_css( $style_variation_node['css'], $style_variation['selector'] );
			}

			// Store variation metadata and node for layout styles generation.
			// Only store if the variation has blockGap defined.
			if ( isset( $style_variation_node['spacing']['blockGap'] ) ) {
				// Append block selector to the variation selector for proper targeting.
				$variation_metadata_with_selector                                = $style_variation;
				$variation_metadata_with_selector['selector']                    = $style_variation['selector'] . $block_metadata['css'];
				$style_variation_layout_metadata[ $style_variation['selector'] ] = array(
					'metadata' => $variation_metadata_with_selector,
					'node'     => $style_variation_node,
				);
			}

			// Store responsive breakpoint CSS for the style variation.
			// This includes both base properties and feature-level selectors.
			$variation_responsive_css        = '';
			$variation_responsive_pseudo_css = '';

			foreach ( array_keys( $responsive_media_queries ) as $breakpoint ) {
				if ( ! isset( $style_variation_node[ $breakpoint ] ) ) {
					continue;
				}

				$breakpoint_node  = $style_variation_node[ $breakpoint ];
				$breakpoint_media = $responsive_media_queries[ $breakpoint ];
				// Process feature-level declarations for this breakpoint.
				$breakpoint_feature_declarations = static::get_feature_declarations_for_node( $block_metadata, $breakpoint_node );
				$breakpoint_feature_declarations = static::update_paragraph_text_indent_selector( $breakpoint_feature_declarations, $settings, $block_name );
				$breakpoint_feature_declarations = static::update_button_width_declarations( $breakpoint_feature_declarations, $settings );
				foreach ( $breakpoint_feature_declarations as $feature_selector => $feature_decl ) {
					$combined_selectors = static::get_block_style_variation_feature_selector( $style_variation, $feature_selector );

					$feature_ruleset           = static::to_ruleset( ':root :where(' . $combined_selectors . ')', $feature_decl );
					$variation_responsive_css .= $breakpoint_media . '{' . $feature_ruleset . '}';
				}

				// Process base properties for this breakpoint.
				$breakpoint_declarations = static::compute_style_properties( $breakpoint_node, $settings, null, $this->theme_json );
				if ( ! empty( $breakpoint_declarations ) ) {
					$base_ruleset              = static::to_ruleset( ':root :where(' . $style_variation['selector'] . ')', $breakpoint_declarations );
					$variation_responsive_css .= $breakpoint_media . '{' . $base_ruleset . '}';
				}

				$breakpoint_pseudo_declarations = $this->process_pseudo_selectors( $breakpoint_node, $style_variation['selector'], $settings, $block_name, $block_metadata, $style_variation );
				foreach ( $breakpoint_pseudo_declarations as $pseudo_selector => $pseudo_declarations ) {
					if ( empty( $pseudo_declarations ) ) {
						continue;
					}
					$pseudo_ruleset                   = static::to_ruleset( ':root :where(' . $pseudo_selector . ')', $pseudo_declarations );
					$variation_responsive_pseudo_css .= $breakpoint_media . '{' . $pseudo_ruleset . '}';
				}

				// Process custom CSS for this breakpoint.
				if ( isset( $breakpoint_node['css'] ) ) {
					$breakpoint_custom_css     = static::process_blocks_custom_css( $breakpoint_node['css'], $style_variation['selector'] );
					$variation_responsive_css .= $breakpoint_media . '{' . $breakpoint_custom_css . '}';
				}

				// Process blockGap responsive layout styles for this variation.
				if ( isset( $breakpoint_node['spacing']['blockGap'] ) ) {
					$variation_layout_metadata             = $style_variation;
					$variation_layout_metadata['selector'] = $style_variation['selector'] . $block_metadata['css'];
					$variation_responsive_css             .= $this->get_layout_styles(
						$variation_layout_metadata,
						array(
							'node'        => $breakpoint_node,
							'media_query' => $breakpoint_media,
						)
					);
				}

				// Process nested element styles for this breakpoint state.
				if ( isset( $breakpoint_node['elements'] ) && ! empty( $block_elements ) ) {
					foreach ( $breakpoint_node['elements'] as $element_name => $element_node ) {
						if ( ! isset( $block_elements[ $element_name ] ) ) {
							continue;
						}

						$variation_element_selector = static::get_block_style_variation_feature_selector( $style_variation, $block_elements[ $element_name ] );

						$element_declarations = static::compute_style_properties( $element_node, $settings, null, $this->theme_json );
						if ( ! empty( $element_declarations ) ) {
							$element_ruleset           = static::to_ruleset( ':root :where(' . $variation_element_selector . ')', $element_declarations );
							$variation_responsive_css .= $breakpoint_media . '{' . $element_ruleset . '}';
						}

						if ( isset( $element_node['css'] ) ) {
							$element_custom_css        = static::process_blocks_custom_css( $element_node['css'], $variation_element_selector );
							$variation_responsive_css .= $breakpoint_media . '{' . $element_custom_css . '}';
						}

						if ( isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] ) ) {
							foreach ( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $element_name ] as $pseudo_selector ) {
								if ( ! isset( $element_node[ $pseudo_selector ] ) ) {
									continue;
								}

								$pseudo_declarations = static::compute_style_properties( $element_node[ $pseudo_selector ], $settings, null, $this->theme_json );
								if ( empty( $pseudo_declarations ) ) {
									continue;
								}

								$pseudo_selector_ruleset          = static::to_ruleset( ':root :where(' . static::append_to_selector( $variation_element_selector, $pseudo_selector ) . ')', $pseudo_declarations );
								$variation_responsive_pseudo_css .= $breakpoint_media . '{' . $pseudo_selector_ruleset . '}';
							}
						}
					}
				}
			}

			if ( ! empty( $variation_responsive_css ) ) {
				$style_variation_responsive_css[ $style_variation['selector'] ] = $variation_responsive_css;
			}
			if ( ! empty( $variation_responsive_pseudo_css ) ) {
				$style_variation_responsive_pseudo_css[ $style_variation['selector'] ] = $variation_responsive_pseudo_css;
			}
		}
	}
	/*
	 * Get a reference to element name from path.
	 * $block_metadata['path'] = array( 'styles','elements','link' );
	 * Make sure that $block_metadata['path'] describes an element node, like [ 'styles', 'element', 'link' ].
	 * Skip non-element paths like just ['styles'].
	 */
	$is_processing_element = in_array( 'elements', $block_metadata['path'], true );

	$current_element = $is_processing_element ? array_last( $block_metadata['path'] ) : null;

	$element_pseudo_allowed = array();

	if ( isset( $current_element, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] ) ) {
		$element_pseudo_allowed = static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ];
	}

	/*
	 * Check for allowed pseudo classes (e.g. ":hover") from the $selector ("a:hover").
	 * This also resets the array keys.
	 */
	$pseudo_matches = array_values(
		array_filter(
			$element_pseudo_allowed,
			static function ( $pseudo_selector ) use ( $selector ) {
				/*
				 * Check if the pseudo selector is in the current selector,
				 * ensuring it is not followed by a dash (e.g., :focus should not match :focus-visible).
				 */
				return preg_match( '/' . preg_quote( $pseudo_selector, '/' ) . '(?!-)/', $selector ) === 1;
			}
		)
	);

	$pseudo_selector = $pseudo_matches[0] ?? null;

	/*
	 * If the current selector is a pseudo selector that's defined in the allow list for the current
	 * element then compute the style properties for it.
	 * Otherwise just compute the styles for the default selector as normal.
	 */
	if ( $pseudo_selector && isset( $node[ $pseudo_selector ] ) &&
		isset( static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ] )
		&& in_array( $pseudo_selector, static::VALID_ELEMENT_PSEUDO_SELECTORS[ $current_element ], true )
	) {
		$declarations = static::compute_style_properties( $node[ $pseudo_selector ], $settings, null, $this->theme_json, $selector, $use_root_padding );
	} else {
		/*
		 * For block pseudo-selector nodes (e.g. ':hover'), $node has already had any
		 * feature-selector properties (e.g. writingMode) removed by get_feature_declarations_for_node,
		 * so those properties are not output twice.
		 */
		$declarations = static::compute_style_properties( $node, $settings, null, $this->theme_json, $selector, $use_root_padding );
	}

	$block_rules = '';

	/*
	 * 1. Bespoke declaration modifiers:
	 * - 'filter': Separate the declarations that use the general selector
	 * from the ones using the duotone selector.
	 * - 'background|background-image': set the html min-height to 100%
	 * to ensure the background covers the entire viewport.
	 */
	$declarations_duotone       = array();
	$should_set_root_min_height = false;

	foreach ( $declarations as $index => $declaration ) {
		if ( 'filter' === $declaration['name'] ) {
			/*
			 * 'unset' filters happen when a filter is unset
			 * in the site-editor UI. Because the 'unset' value
			 * in the user origin overrides the value in the
			 * theme origin, we can skip rendering anything
			 * here as no filter needs to be applied anymore.
			 * So only add declarations to with values other
			 * than 'unset'.
			 */
			if ( 'unset' !== $declaration['value'] ) {
				$declarations_duotone[] = $declaration;
			}
			unset( $declarations[ $index ] );
		}

		if ( $is_root_selector && ( 'background-image' === $declaration['name'] || 'background' === $declaration['name'] ) ) {
			$should_set_root_min_height = true;
		}
	}

	/*
	 * If root styles has a background-image or a background (gradient) set,
	 * set the min-height to '100%'. Minus `--wp-admin--admin-bar--height` for logged-in view.
	 * Setting the CSS rule on the HTML tag ensures background gradients and images behave similarly,
	 * and matches the behavior of the site editor.
	 */
	if ( $should_set_root_min_height ) {
		$block_rules .= static::to_ruleset(
			'html',
			array(
				array(
					'name'  => 'min-height',
					'value' => 'calc(100% - var(--wp-admin--admin-bar--height, 0px))',
				),
			)
		);
	}

	// Update declarations if there are separators with only background color defined.
	if ( '.wp-block-separator' === $selector ) {
		$declarations = static::update_separator_declarations( $declarations );
	}

	/*
	 * Root selector (body) styles should not be wrapped in `:root where()` to keep
	 * specificity at (0,0,1) and maintain backwards compatibility.
	 *
	 * Top-level element styles using element-only specificity selectors should
	 * not get wrapped in `:root :where()` to maintain backwards compatibility.
	 *
	 * Pseudo classes, e.g. :hover, :focus etc., are a class-level selector so
	 * still need to be wrapped in `:root :where` to cap specificity for nested
	 * variations etc. Pseudo selectors won't match the ELEMENTS selector exactly.
	 */
	$element_only_selector = $is_root_selector || (
		$current_element &&
		isset( static::ELEMENTS[ $current_element ] ) &&
		// buttons, captions etc. still need `:root :where()` as they are class based selectors.
		! isset( static::__EXPERIMENTAL_ELEMENT_CLASS_NAMES[ $current_element ] ) &&
		static::ELEMENTS[ $current_element ] === $selector
	);

	// 2. Generate and append the rules that use the general selector.
	$general_selector = $element_only_selector ? $selector : ":root :where($selector)";
	$block_rules     .= static::to_ruleset( $general_selector, $declarations );

	// 3. Generate and append the rules that use the duotone selector.
	if ( isset( $block_metadata['duotone'] ) && ! empty( $declarations_duotone ) ) {
		$block_rules .= static::to_ruleset( $block_metadata['duotone'], $declarations_duotone );
	}

	// 4. Generate Layout block gap styles.
	if (
		! $is_root_selector &&
		! empty( $block_metadata['name'] )
	) {
		$block_rules .= $this->get_layout_styles( $block_metadata );
	}

	// 5. Generate and append the feature level rulesets.
	foreach ( $feature_declarations as $feature_selector => $individual_feature_declarations ) {
		$block_rules .= static::to_ruleset( ":root :where($feature_selector)", $individual_feature_declarations );
	}

	// 6. Generate and append the style variation rulesets.
	foreach ( $style_variation_declarations as $style_variation_selector => $individual_style_variation_declarations ) {
		$block_rules .= static::to_ruleset( ":root :where($style_variation_selector)", $individual_style_variation_declarations );
		if ( isset( $style_variation_layout_metadata[ $style_variation_selector ] ) ) {
			$variation_data = $style_variation_layout_metadata[ $style_variation_selector ];
			$block_rules   .= $this->get_layout_styles( $variation_data['metadata'], array( 'node' => $variation_data['node'] ) );
		}
		if ( isset( $style_variation_custom_css[ $style_variation_selector ] ) ) {
			$block_rules .= $style_variation_custom_css[ $style_variation_selector ];
		}
		if ( isset( $style_variation_responsive_css[ $style_variation_selector ] ) ) {
			$block_rules .= $style_variation_responsive_css[ $style_variation_selector ];
		}
	}
	/*
	 * Responsive pseudo styles must be output after default pseudo styles
	 * so viewport state styles win in the cascade.
	 */
	foreach ( $style_variation_responsive_pseudo_css as $responsive_pseudo_css ) {
		$block_rules .= $responsive_pseudo_css;
	}

	// 7. Generate and append any custom CSS rules.
	if ( isset( $node['css'] ) && ! $is_root_selector ) {
		$css_feature_selector = $block_metadata['selectors']['css'] ?? null;
		if ( is_array( $css_feature_selector ) ) {
			$css_feature_selector = $css_feature_selector['root'] ?? null;
		}
		$css_selector = is_string( $css_feature_selector ) ? $css_feature_selector : $selector;
		$block_rules .= $this->process_blocks_custom_css( $node['css'], $css_selector );
	}

	// 8. Wrap the entire block output in a media query if this is a responsive node.
	// Responsive nodes are created by get_block_nodes() for each breakpoint and carry
	// a 'media_query' key.
	if ( $media_query && ! empty( $block_rules ) ) {
		$block_rules = $media_query . '{' . $block_rules . '}';
	}

	return $block_rules;
}