| 1 |
<?php |
| 2 |
/** |
| 3 |
* Server-side rendering of the `core/post-excerpt` block. |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Renders the `core/post-excerpt` 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 filtered post excerpt for the current post wrapped inside "p" tags. |
| 15 |
*/ |
| 16 |
function gutenberg_render_block_core_post_excerpt( $attributes, $content, $block ) { |
| 17 |
if ( ! isset( $block->context['postId'] ) ) { |
| 18 |
return ''; |
| 19 |
} |
| 20 |
|
| 21 |
$more_text = isset( $attributes['moreText'] ) ? '<a class="wp-block-post-excerpt__more-link" href="' . esc_url( get_the_permalink( $block->context['postId'] ) ) . '">' . $attributes['moreText'] . '</a>' : ''; |
| 22 |
|
| 23 |
$filter_excerpt_length = function() use ( $attributes ) { |
| 24 |
return isset( $attributes['wordCount'] ) ? $attributes['wordCount'] : 55; |
| 25 |
}; |
| 26 |
add_filter( |
| 27 |
'excerpt_length', |
| 28 |
$filter_excerpt_length |
| 29 |
); |
| 30 |
|
| 31 |
$classes = ''; |
| 32 |
if ( isset( $attributes['textAlign'] ) ) { |
| 33 |
$classes .= 'has-text-align-' . $attributes['textAlign']; |
| 34 |
} |
| 35 |
$wrapper_attributes = get_block_wrapper_attributes( array( 'class' => $classes ) ); |
| 36 |
|
| 37 |
$content = '<p class="wp-block-post-excerpt__excerpt">' . get_the_excerpt( $block->context['postId'] ); |
| 38 |
if ( ! isset( $attributes['showMoreOnNewLine'] ) || $attributes['showMoreOnNewLine'] ) { |
| 39 |
$content .= '</p><p class="wp-block-post-excerpt__more-text">' . $more_text . '</p>'; |
| 40 |
} else { |
| 41 |
$content .= " $more_text</p>"; |
| 42 |
} |
| 43 |
|
| 44 |
remove_filter( |
| 45 |
'excerpt_length', |
| 46 |
$filter_excerpt_length |
| 47 |
); |
| 48 |
|
| 49 |
return sprintf( '<div %1$s>%2$s</div>', $wrapper_attributes, $content ); |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Registers the `core/post-excerpt` block on the server. |
| 54 |
*/ |
| 55 |
function gutenberg_register_block_core_post_excerpt() { |
| 56 |
register_block_type_from_metadata( |
| 57 |
__DIR__ . '/post-excerpt', |
| 58 |
array( |
| 59 |
'render_callback' => 'gutenberg_render_block_core_post_excerpt', |
| 60 |
) |
| 61 |
); |
| 62 |
} |
| 63 |
add_action( 'init', 'gutenberg_register_block_core_post_excerpt', 20 ); |
| 64 |
|