post-excerpt.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * Server-side rendering of the `core/post-excerpt` block.
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Renders the `core/post-excerpt` block on the server.
  9. *
  10. * @param array $attributes Block attributes.
  11. * @param string $content Block default content.
  12. * @param WP_Block $block Block instance.
  13. * @return string Returns the filtered post excerpt for the current post wrapped inside "p" tags.
  14. */
  15. function render_block_core_post_excerpt( $attributes, $content, $block ) {
  16. if ( ! isset( $block->context['postId'] ) ) {
  17. return '';
  18. }
  19. $excerpt = get_the_excerpt();
  20. if ( empty( $excerpt ) ) {
  21. return '';
  22. }
  23. $more_text = ! empty( $attributes['moreText'] ) ? '<a class="wp-block-post-excerpt__more-link" href="' . esc_url( get_the_permalink( $block->context['postId'] ) ) . '">' . wp_kses_post( $attributes['moreText'] ) . '</a>' : '';
  24. $filter_excerpt_more = function( $more ) use ( $more_text ) {
  25. return empty( $more_text ) ? $more : '';
  26. };
  27. /**
  28. * Some themes might use `excerpt_more` filter to handle the
  29. * `more` link displayed after a trimmed excerpt. Since the
  30. * block has a `more text` attribute we have to check and
  31. * override if needed the return value from this filter.
  32. * So if the block's attribute is not empty override the
  33. * `excerpt_more` filter and return nothing. This will
  34. * result in showing only one `read more` link at a time.
  35. */
  36. add_filter( 'excerpt_more', $filter_excerpt_more );
  37. $classes = '';
  38. if ( isset( $attributes['textAlign'] ) ) {
  39. $classes .= "has-text-align-{$attributes['textAlign']}";
  40. }
  41. $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => $classes ) );
  42. $content = '<p class="wp-block-post-excerpt__excerpt">' . $excerpt;
  43. $show_more_on_new_line = ! isset( $attributes['showMoreOnNewLine'] ) || $attributes['showMoreOnNewLine'];
  44. if ( $show_more_on_new_line && ! empty( $more_text ) ) {
  45. $content .= '</p><p class="wp-block-post-excerpt__more-text">' . $more_text . '</p>';
  46. } else {
  47. $content .= " $more_text</p>";
  48. }
  49. remove_filter( 'excerpt_more', $filter_excerpt_more );
  50. return sprintf( '<div %1$s>%2$s</div>', $wrapper_attributes, $content );
  51. }
  52. /**
  53. * Registers the `core/post-excerpt` block on the server.
  54. */
  55. function register_block_core_post_excerpt() {
  56. register_block_type_from_metadata(
  57. __DIR__ . '/post-excerpt',
  58. array(
  59. 'render_callback' => 'render_block_core_post_excerpt',
  60. )
  61. );
  62. }
  63. add_action( 'init', 'register_block_core_post_excerpt' );