Skip to content
Next Next commit
Adding a server render_callback in order to add a data-id attribute t…
…o the image element.

Check for existing data-id attribute on the image block content
Wrapping $attributes['id'] in an isset check to catch undefined indexes
  • Loading branch information
ramonjd committed Nov 5, 2021
commit b0cddec62f1079296de8a2cfed9e63ddc2edacc9
2 changes: 2 additions & 0 deletions lib/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ function gutenberg_reregister_core_block_types() {
'comment-template.php' => 'core/comment-template',
'file.php' => 'core/file',
'home-link.php' => 'core/home-link',
'image.php' => 'core/image',
'gallery.php' => 'core/gallery',
'latest-comments.php' => 'core/latest-comments',
'latest-posts.php' => 'core/latest-posts',
'loginout.php' => 'core/loginout',
Expand Down
40 changes: 40 additions & 0 deletions packages/block-library/src/image/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
/**
* Server-side rendering of the `core/image` block.
*
* @package gutenberg
*/

/**
* Renders the `core/image` block on the server.
*
* @param array $attributes The block attributes.
* @param array $content The block content.
* @return string Returns the block content with the data-id attribute added.
*/
function render_block_core_image( $attributes, $content ) {
if ( isset( $attributes['id'] ) ) {
// Add the data-id="$id" attribute to the img element
// to provide backwards compatibility for the Gallery Block,
// which now wraps Image Blocks within innerBlocks.
$data_id_attribute = 'data-id="' . esc_attr( $attributes['id'] ) . '"';
if ( ! strpos( $content, $data_id_attribute ) ) {
$content = str_replace( '<img', '<img ' . $data_id_attribute . ' ', $content );
}
}
return $content;
}


/**
* Register image block.
*/
function register_block_core_image() {
register_block_type_from_metadata(
__DIR__ . '/image',
array(
'render_callback' => 'render_block_core_image',
)
);
}
add_action( 'init', 'register_block_core_image' );