image.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. /**
  3. * Server-side rendering of the `core/image` block.
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Renders the `core/image` block on the server,
  9. * adding a data-id attribute to the element if core/gallery has added on pre-render.
  10. *
  11. * @param array $attributes The block attributes.
  12. * @param string $content The block content.
  13. * @return string Returns the block content with the data-id attribute added.
  14. */
  15. function render_block_core_image( $attributes, $content ) {
  16. if ( isset( $attributes['data-id'] ) ) {
  17. // Add the data-id="$id" attribute to the img element
  18. // to provide backwards compatibility for the Gallery Block,
  19. // which now wraps Image Blocks within innerBlocks.
  20. // The data-id attribute is added in a core/gallery `render_block_data` hook.
  21. $data_id_attribute = 'data-id="' . esc_attr( $attributes['data-id'] ) . '"';
  22. if ( ! str_contains( $content, $data_id_attribute ) ) {
  23. $content = str_replace( '<img', '<img ' . $data_id_attribute . ' ', $content );
  24. }
  25. }
  26. return $content;
  27. }
  28. /**
  29. * Registers the `core/image` block on server.
  30. */
  31. function register_block_core_image() {
  32. register_block_type_from_metadata(
  33. __DIR__ . '/image',
  34. array(
  35. 'render_callback' => 'render_block_core_image',
  36. )
  37. );
  38. }
  39. add_action( 'init', 'register_block_core_image' );