| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side rendering of the `core/post-featured-image` block. |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Renders the `core/post-featured-image` block on the server. |
| 10 |
* |
| 11 |
* @param array $attributes Block attributes. |
| 12 |
* @param string $content Block default content. |
| 13 |
* @param WP_Block $block Block instance. |
| 14 |
* @return string Returns the featured image for the current post. |
| 15 |
*/ |
| 16 |
function gutenberg_render_block_core_post_featured_image( $attributes, $content, $block ) { |
| 17 |
if ( ! isset( $block->context['postId'] ) ) { |
| 18 |
return ''; |
| 19 |
} |
| 20 |
$post_ID = $block->context['postId']; |
| 21 |
|
| 22 |
$size_slug = isset( $attributes['sizeSlug'] ) ? $attributes['sizeSlug'] : 'post-thumbnail'; |
| 23 |
$featured_image = get_the_post_thumbnail( $post_ID, $size_slug ); |
| 24 |
if ( ! $featured_image ) { |
| 25 |
return ''; |
| 26 |
} |
| 27 |
$wrapper_attributes = get_block_wrapper_attributes(); |
| 28 |
if ( isset( $attributes['isLink'] ) && $attributes['isLink'] ) { |
| 29 |
$featured_image = sprintf( '<a href="%1s">%2s</a>', get_the_permalink( $post_ID ), $featured_image ); |
| 30 |
} |
| 31 |
|
| 32 |
$has_width = ! empty( $attributes['width'] ); |
| 33 |
$has_height = ! empty( $attributes['height'] ); |
| 34 |
if ( ! $has_height && ! $has_width ) { |
| 35 |
return "<figure $wrapper_attributes>$featured_image</figure>"; |
| 36 |
} |
| 37 |
|
| 38 |
if ( $has_width ) { |
| 39 |
$wrapper_attributes = get_block_wrapper_attributes( array( 'style' => "width:{$attributes['width']};" ) ); |
| 40 |
} |
| 41 |
|
| 42 |
if ( $has_height ) { |
| 43 |
$image_styles = "height:{$attributes['height']};"; |
| 44 |
if ( ! empty( $attributes['scale'] ) ) { |
| 45 |
$image_styles .= "object-fit:{$attributes['scale']};"; |
| 46 |
} |
| 47 |
$featured_image = str_replace( 'src=', 'style="' . esc_attr( $image_styles ) . '" src=', $featured_image ); |
| 48 |
} |
| 49 |
|
| 50 |
return "<figure $wrapper_attributes>$featured_image</figure>"; |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Registers the `core/post-featured-image` block on the server. |
| 55 |
*/ |
| 56 |
function gutenberg_register_block_core_post_featured_image() { |
| 57 |
register_block_type_from_metadata( |
| 58 |
__DIR__ . '/post-featured-image', |
| 59 |
array( |
| 60 |
'render_callback' => 'gutenberg_render_block_core_post_featured_image', |
| 61 |
) |
| 62 |
); |
| 63 |
} |
| 64 |
add_action( 'init', 'gutenberg_register_block_core_post_featured_image', 20 ); |
| 65 |
|