| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side rendering of the `core/post-time-to-read` block. |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Renders the `core/post-time-to-read` 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 rendered post author name block. |
| 15 |
*/ |
| 16 |
function gutenberg_render_block_core_post_time_to_read( $attributes, $content, $block ) { |
| 17 |
if ( ! isset( $block->context['postId'] ) ) { |
| 18 |
return ''; |
| 19 |
} |
| 20 |
|
| 21 |
$content = get_the_content(); |
| 22 |
|
| 23 |
/* |
| 24 |
* Average reading rate - based on average taken from |
| 25 |
* https://irisreading.com/average-reading-speed-in-various-languages/ |
| 26 |
* (Characters/minute used for Chinese rather than words). |
| 27 |
*/ |
| 28 |
$average_reading_rate = 189; |
| 29 |
|
| 30 |
$word_count_type = wp_get_word_count_type(); |
| 31 |
|
| 32 |
$minutes_to_read = max( 1, (int) round( wp_word_count( $content, $word_count_type ) / $average_reading_rate ) ); |
| 33 |
|
| 34 |
$minutes_to_read_string = sprintf( |
| 35 |
/* translators: %s: the number of minutes to read the post. */ |
| 36 |
_n( '%s minute', '%s minutes', $minutes_to_read ), |
| 37 |
$minutes_to_read |
| 38 |
); |
| 39 |
|
| 40 |
$align_class_name = empty( $attributes['textAlign'] ) ? '' : "has-text-align-{$attributes['textAlign']}"; |
| 41 |
|
| 42 |
$wrapper_attributes = get_block_wrapper_attributes( array( 'class' => $align_class_name ) ); |
| 43 |
|
| 44 |
return sprintf( |
| 45 |
'<div %1$s>%2$s</div>', |
| 46 |
$wrapper_attributes, |
| 47 |
$minutes_to_read_string |
| 48 |
); |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Registers the `core/post-time-to-read` block on the server. |
| 53 |
*/ |
| 54 |
function gutenberg_register_block_core_post_time_to_read() { |
| 55 |
register_block_type_from_metadata( |
| 56 |
__DIR__ . '/post-time-to-read', |
| 57 |
array( |
| 58 |
'render_callback' => 'gutenberg_render_block_core_post_time_to_read', |
| 59 |
) |
| 60 |
); |
| 61 |
} |
| 62 |
add_action( 'init', 'gutenberg_register_block_core_post_time_to_read', 20 ); |
| 63 |
|