18
|
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 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 |
|
19
|
22 |
$size_slug = isset( $attributes['sizeSlug'] ) ? $attributes['sizeSlug'] : 'post-thumbnail'; |
|
23 |
$post_title = trim( strip_tags( get_the_title( $post_ID ) ) ); |
|
24 |
$featured_image = get_the_post_thumbnail( $post_ID, $size_slug, array( 'alt' => $post_title ) ); |
18
|
25 |
if ( ! $featured_image ) { |
|
26 |
return ''; |
|
27 |
} |
19
|
28 |
$wrapper_attributes = get_block_wrapper_attributes(); |
18
|
29 |
if ( isset( $attributes['isLink'] ) && $attributes['isLink'] ) { |
|
30 |
$featured_image = sprintf( '<a href="%1s">%2s</a>', get_the_permalink( $post_ID ), $featured_image ); |
|
31 |
} |
|
32 |
|
19
|
33 |
$has_width = ! empty( $attributes['width'] ); |
|
34 |
$has_height = ! empty( $attributes['height'] ); |
|
35 |
if ( ! $has_height && ! $has_width ) { |
|
36 |
return "<figure $wrapper_attributes>$featured_image</figure>"; |
|
37 |
} |
|
38 |
|
|
39 |
if ( $has_width ) { |
|
40 |
$wrapper_attributes = get_block_wrapper_attributes( array( 'style' => "width:{$attributes['width']};" ) ); |
|
41 |
} |
18
|
42 |
|
19
|
43 |
if ( $has_height ) { |
|
44 |
$image_styles = "height:{$attributes['height']};"; |
|
45 |
if ( ! empty( $attributes['scale'] ) ) { |
|
46 |
$image_styles .= "object-fit:{$attributes['scale']};"; |
|
47 |
} |
|
48 |
$featured_image = str_replace( 'src=', 'style="' . esc_attr( $image_styles ) . '" src=', $featured_image ); |
|
49 |
} |
|
50 |
|
|
51 |
return "<figure $wrapper_attributes>$featured_image</figure>"; |
18
|
52 |
} |
|
53 |
|
|
54 |
/** |
|
55 |
* Registers the `core/post-featured-image` block on the server. |
|
56 |
*/ |
|
57 |
function register_block_core_post_featured_image() { |
|
58 |
register_block_type_from_metadata( |
|
59 |
__DIR__ . '/post-featured-image', |
|
60 |
array( |
|
61 |
'render_callback' => 'render_block_core_post_featured_image', |
|
62 |
) |
|
63 |
); |
|
64 |
} |
|
65 |
add_action( 'init', 'register_block_core_post_featured_image' ); |