| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side customizations for the `core/cover` block. |
| 4 |
* |
| 5 |
* @package twentig |
| 6 |
*/ |
| 7 |
|
| 8 |
defined( 'ABSPATH' ) || exit; |
| 9 |
|
| 10 |
/** |
| 11 |
* Filters the cover block output to add responsive image sizes. |
| 12 |
* |
| 13 |
* @param string $block_content Rendered block content. |
| 14 |
* @param array $block Block object. |
| 15 |
* @return string Filtered block content. |
| 16 |
*/ |
| 17 |
function twentig_filter_cover_block( $block_content, $block ) { |
| 18 |
|
| 19 |
$attributes = $block['attrs'] ?? array(); |
| 20 |
$image_id = $attributes['id'] ?? null; |
| 21 |
|
| 22 |
if ( ! $image_id && ! empty( $attributes['useFeaturedImage'] ) ) { |
| 23 |
$image_id = get_post_thumbnail_id(); |
| 24 |
} |
| 25 |
|
| 26 |
if ( ! $image_id ) { |
| 27 |
return $block_content; |
| 28 |
} |
| 29 |
|
| 30 |
$image_meta = wp_get_attachment_metadata( $image_id ); |
| 31 |
|
| 32 |
if ( ! $image_meta || empty( $image_meta['width'] ) ) { |
| 33 |
return $block_content; |
| 34 |
} |
| 35 |
|
| 36 |
$width = absint( $image_meta['width'] ); |
| 37 |
|
| 38 |
if ( ! $width ) { |
| 39 |
return $block_content; |
| 40 |
} |
| 41 |
|
| 42 |
$sizes = sprintf( |
| 43 |
'(max-width: 799px) 200vw, (max-width: %1$dpx) 100vw, %1$dpx', |
| 44 |
$width |
| 45 |
); |
| 46 |
|
| 47 |
if ( ! empty( $attributes['style']['dimensions']['aspectRatio'] ) ) { |
| 48 |
$sizes = sprintf( |
| 49 |
'(max-width: 799px) 125vw, (max-width: %1$dpx) 100vw, %1$dpx', |
| 50 |
$width |
| 51 |
); |
| 52 |
} |
| 53 |
|
| 54 |
$tag_processor = new WP_HTML_Tag_Processor( $block_content ); |
| 55 |
|
| 56 |
if ( $tag_processor->next_tag( 'img' ) ) { |
| 57 |
$tag_processor->set_attribute( 'sizes', $sizes ); |
| 58 |
$block_content = $tag_processor->get_updated_html(); |
| 59 |
} |
| 60 |
|
| 61 |
return $block_content; |
| 62 |
} |
| 63 |
add_filter( 'render_block_core/cover', 'twentig_filter_cover_block', 10, 2 ); |
| 64 |
|