| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side rendering of the `core/details` block. |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Sets fetchpriority="low" on all IMG tags within the collapsed Details block. |
| 10 |
* |
| 11 |
* Images in a collapsed Details block are hidden until the block is expanded, so they should |
| 12 |
* not compete with any resources in the critical rendering path, such as the LCP element image. |
| 13 |
* |
| 14 |
* @since 7.0.0 |
| 15 |
* |
| 16 |
* @param string $block_content The block content. |
| 17 |
* @param array $block The full block, including name and attributes. |
| 18 |
* @return string Modified HTML with fetchpriority="low" on all IMG tags when the showContent attribute is false. |
| 19 |
*/ |
| 20 |
function gutenberg_block_core_details_set_img_fetchpriority_low( $block_content, array $block ): string { |
| 21 |
if ( ! is_string( $block_content ) ) { |
| 22 |
return ''; |
| 23 |
} |
| 24 |
|
| 25 |
// If the Details block is open by default, short-circuit to let core add fetchpriority=high if appropriate. |
| 26 |
if ( $block['attrs']['showContent'] ?? false ) { |
| 27 |
return $block_content; |
| 28 |
} |
| 29 |
|
| 30 |
$tags = new WP_HTML_Tag_Processor( $block_content ); |
| 31 |
while ( $tags->next_tag( 'IMG' ) ) { |
| 32 |
$tags->set_attribute( 'fetchpriority', 'low' ); |
| 33 |
} |
| 34 |
return $tags->get_updated_html(); |
| 35 |
} |
| 36 |
|
| 37 |
add_filter( 'render_block_core/details', 'gutenberg_block_core_details_set_img_fetchpriority_low', 10, 2 ); |
| 38 |
|
| 39 |
/** |
| 40 |
* Registers the `core/details` block on server. |
| 41 |
* |
| 42 |
* @since 7.0.0 |
| 43 |
*/ |
| 44 |
function gutenberg_register_block_core_details() { |
| 45 |
register_block_type_from_metadata( __DIR__ . '/details' ); |
| 46 |
} |
| 47 |
add_action( 'init', 'gutenberg_register_block_core_details', 20 ); |
| 48 |
|