file.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /**
  3. * Server-side rendering of the `core/file` block.
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * When the `core/file` block is rendering, check if we need to enqueue the `'wp-block-file-view` script.
  9. *
  10. * @param array $attributes The block attributes.
  11. * @param string $content The block content.
  12. *
  13. * @return string Returns the block content.
  14. */
  15. function render_block_core_file( $attributes, $content ) {
  16. $should_load_view_script = ! empty( $attributes['displayPreview'] ) && ! wp_script_is( 'wp-block-file-view' );
  17. if ( $should_load_view_script ) {
  18. wp_enqueue_script( 'wp-block-file-view' );
  19. }
  20. // Update object's aria-label attribute if present in block HTML.
  21. // Match an aria-label attribute from an object tag.
  22. $pattern = '@<object.+(?<attribute>aria-label="(?<filename>[^"]+)?")@i';
  23. $content = preg_replace_callback(
  24. $pattern,
  25. function ( $matches ) {
  26. $filename = ! empty( $matches['filename'] ) ? $matches['filename'] : '';
  27. $has_filename = ! empty( $filename ) && 'PDF embed' !== $filename;
  28. $label = $has_filename ?
  29. sprintf(
  30. /* translators: %s: filename. */
  31. __( 'Embed of %s.' ),
  32. $filename
  33. )
  34. : __( 'PDF embed' );
  35. return str_replace( $matches['attribute'], sprintf( 'aria-label="%s"', $label ), $matches[0] );
  36. },
  37. $content
  38. );
  39. return $content;
  40. }
  41. /**
  42. * Registers the `core/file` block on server.
  43. */
  44. function register_block_core_file() {
  45. register_block_type_from_metadata(
  46. __DIR__ . '/file',
  47. array(
  48. 'render_callback' => 'render_block_core_file',
  49. )
  50. );
  51. }
  52. add_action( 'init', 'register_block_core_file' );