| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side rendering of the `core/cover` block. |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Renders the `core/cover` block on server. |
| 10 |
* |
| 11 |
* @param array $attributes The block attributes. |
| 12 |
* @param array $content The block rendered content. |
| 13 |
* |
| 14 |
* @return string Returns the cover block markup, if useFeaturedImage is true. |
| 15 |
*/ |
| 16 |
function gutenberg_render_block_core_cover( $attributes, $content ) { |
| 17 |
if ( 'image' !== $attributes['backgroundType'] || false === $attributes['useFeaturedImage'] ) { |
| 18 |
return $content; |
| 19 |
} |
| 20 |
|
| 21 |
if ( ! ( $attributes['hasParallax'] || $attributes['isRepeated'] ) ) { |
| 22 |
$attr = array( |
| 23 |
'class' => 'wp-block-cover__image-background', |
| 24 |
'data-object-fit' => 'cover', |
| 25 |
); |
| 26 |
|
| 27 |
if ( isset( $attributes['focalPoint'] ) ) { |
| 28 |
$object_position = round( $attributes['focalPoint']['x'] * 100 ) . '%' . ' ' . round( $attributes['focalPoint']['y'] * 100 ) . '%'; |
| 29 |
$attr['data-object-position'] = $object_position; |
| 30 |
$attr['style'] = 'object-position: ' . $object_position; |
| 31 |
} |
| 32 |
|
| 33 |
$image = get_the_post_thumbnail( null, 'post-thumbnail', $attr ); |
| 34 |
|
| 35 |
$content = str_replace( |
| 36 |
'</span><div', |
| 37 |
'</span>' . $image . '<div', |
| 38 |
$content |
| 39 |
); |
| 40 |
|
| 41 |
} else { |
| 42 |
if ( in_the_loop() ) { |
| 43 |
update_post_thumbnail_cache(); |
| 44 |
} |
| 45 |
$current_featured_image = get_the_post_thumbnail_url(); |
| 46 |
$content = preg_replace( |
| 47 |
'/class=\".*?\"/', |
| 48 |
'${0} style="background-image:url(' . esc_url( $current_featured_image ) . ')"', |
| 49 |
$content, |
| 50 |
1 |
| 51 |
); |
| 52 |
} |
| 53 |
|
| 54 |
return $content; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Registers the `core/cover` block renderer on server. |
| 59 |
*/ |
| 60 |
function gutenberg_register_block_core_cover() { |
| 61 |
register_block_type_from_metadata( |
| 62 |
__DIR__ . '/cover', |
| 63 |
array( |
| 64 |
'render_callback' => 'gutenberg_render_block_core_cover', |
| 65 |
) |
| 66 |
); |
| 67 |
} |
| 68 |
add_action( 'init', 'gutenberg_register_block_core_cover', 20 ); |
| 69 |
|