Method_CSS_Collector
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
| Property | Visibility | Type | Description |
|---|---|---|---|
$instance | private static | ?self | Singleton instance |
$styles | private | array | Collected CSS entries keyed by block ID |
$flushed | private | array | Keys already printed, so the footer flush skips them |
$flush_count | private | int | How 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.
| Param | Type | Description |
|---|---|---|
$css | string | CSS rules without <style> tags. |
$block_id | string | Optional unique ID to prevent duplicates. |
$priority | int | Sort order — lower numbers output first. Default 10. |
Notes:
- CSS added after the head flush is printed by the footer flush; CSS added after
wp_footerpriority 20 is never printed. A call without a$block_idis keyed withuniqid(). - Duplicate
$block_idvalues 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
method_collect_css( string $css, string $block_id = '', int $priority = 10 ): void
Convenience wrapper: Method_CSS_Collector::instance()->add( $css, $block_id, $priority ).
Usage
// In a block render callback:
$css = method_get_block_responsive_styles( $attrs, $cssargs, ['base', 'mobile', 'tablet', 'wide'], false );
method_collect_css( $css, '#' . $methodId, 10 );