Overview

Singleton that collects CSS from block render callbacks and outputs a single consolidated <style> tag.


Description

Blocks in Method generate scoped CSS during their PHP render callbacks. Rather than each block outputting its own <style> tag, all CSS is collected by this singleton and printed in wp_head at priority 100 — after the block template has rendered — with a second flush on wp_footer at priority 20 that prints whatever was collected later (navigation panels, hooks, blocks rendered during the template). Each key is printed once.

CSS is automatically minified in production (when WP_DEBUG is not true).


Source

File: lib/class-method-css-collector.php


Properties

PropertyVisibilityTypeDescription
$instanceprivate static?selfSingleton instance
$stylesprivatearrayCollected CSS entries keyed by block ID
$flushedprivatearrayKeys already printed, so the footer flush skips them
$flush_countprivateintHow many flushes have run

Methods

instance(): self (static)

Returns the singleton instance. Creates it on first call.


add( string $css, string $block_id = '', int $priority = 10 ): void

Adds CSS from a block render callback.

ParamTypeDescription
$cssstringCSS rules without <style> tags.
$block_idstringOptional unique ID to prevent duplicates.
$priorityintSort order — lower numbers output first. Default 10.

Notes:

  • CSS added after the head flush is printed by the footer flush; CSS added after wp_footer priority 20 is never printed. A call without a $block_id is keyed with uniqid().
  • Duplicate $block_id values are ignored.

output_styles(): void

Sorts collected CSS by priority, concatenates, optionally minifies, and outputs as <style id="block-instance-styles">. Hooked to wp_head at priority 100 and again to wp_footer at priority 20; already-flushed keys are skipped.


minify( string $css ): string (private)

Strips comments, collapses whitespace, and removes spaces around CSS punctuation.


Global Helper

PHP
method_collect_css( string $css, string $block_id = '', int $priority = 10 ): void

Convenience wrapper: Method_CSS_Collector::instance()->add( $css, $block_id, $priority ).


Usage

PHP
// In a block render callback:
$css = method_get_block_responsive_styles( $attrs, $cssargs, ['base', 'mobile', 'tablet', 'wide'], false );
method_collect_css( $css, '#' . $methodId, 10 );

Changelog

VersionDescription
2.0.0-alpha5Introduced (98254e8).
2.0.0-beta17Second flush on wp_footer (priority 20) for CSS collected after the head; CSS is no longer discarded after the first output, and flushed keys are tracked (cce9f89).