wp_render_custom_css_support_styles()WP 7.0.0

Render the custom CSS stylesheet and add class name to block as required.

No Hooks.

Returns

array. The same parsed block with custom CSS class name added if appropriate.

Usage

wp_render_custom_css_support_styles( $parsed_block );
$parsed_block(array) (required)
The parsed block.

Changelog

Since 7.0.0 Introduced.

wp_render_custom_css_support_styles() code WP 7.1

function wp_render_custom_css_support_styles( $parsed_block ) {
	$custom_css = $parsed_block['attrs']['style']['css'] ?? null;
	if ( ! is_string( $custom_css ) || '' === trim( $custom_css ) ) {
		return $parsed_block;
	}

	$block_type = WP_Block_Type_Registry::get_instance()->get_registered( $parsed_block['blockName'] );
	if ( ! block_has_support( $block_type, 'customCSS', true ) ) {
		return $parsed_block;
	}

	// Validate CSS doesn't contain HTML markup (same validation as global styles REST API).
	if ( preg_match( '#</?\w+#', $custom_css ) ) {
		return $parsed_block;
	}

	// Generate a unique class name for this block instance.
	$class_name          = wp_unique_id_from_values( $parsed_block, 'wp-custom-css-' );
	$existing_class_name = $parsed_block['attrs']['className'] ?? null;
	$updated_class_name  = is_string( $existing_class_name )
		? "$existing_class_name $class_name"
		: $class_name;

	$parsed_block['attrs']['className'] = $updated_class_name;

	// Process the custom CSS using the same method as global styles.
	$selector      = '.' . $class_name;
	$processed_css = WP_Theme_JSON::process_blocks_custom_css( $custom_css, $selector );

	if ( ! empty( $processed_css ) ) {
		/**
		 * Reuse one handle so identical custom CSS is enqueued only once via
		 * {@see wp_unique_id_from_values()}. Explicitly declare the `wp-block-library`
		 * dependency so `global-styles` is guaranteed to print after it, preventing
		 * block default styles from unintentionally overriding global styles.
		 */
		$handle = 'wp-block-custom-css';
		if ( ! wp_style_is( $handle, 'registered' ) ) {
			wp_register_style( $handle, false, array( 'wp-block-library', 'global-styles' ) );
		}
		$after_styles = wp_styles()->get_data( $handle, 'after' );
		if ( ! is_array( $after_styles ) ) {
			$after_styles = array();
		}
		if ( ! in_array( $processed_css, $after_styles, true ) ) {
			wp_add_inline_style( $handle, $processed_css );
		}
	}

	return $parsed_block;
}