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