Sin descripción

post-excerpt.php 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. $more_text = ! empty( $attributes['moreText'] ) ? '<a class="wp-block-post-excerpt__more-link" href="' . esc_url( get_the_permalink( $block->context['postId'] ) ) . '">' . $attributes['moreText'] . '</a>' : '';
  20. $filter_excerpt_more = function( $more ) use ( $more_text ) {
  21. return empty( $more_text ) ? $more : '';
  22. };
  23. /**
  24. * Some themes might use `excerpt_more` filter to handle the
  25. * `more` link displayed after a trimmed excerpt. Since the
  26. * block has a `more text` attribute we have to check and
  27. * override if needed the return value from this filter.
  28. * So if the block's attribute is not empty override the
  29. * `excerpt_more` filter and return nothing. This will
  30. * result in showing only one `read more` link at a time.
  31. */
  32. add_filter( 'excerpt_more', $filter_excerpt_more );
  33. $classes = '';
  34. if ( isset( $attributes['textAlign'] ) ) {
  35. $classes .= "has-text-align-{$attributes['textAlign']}";
  36. }
  37. $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => $classes ) );
  38. $content = '<p class="wp-block-post-excerpt__excerpt">' . get_the_excerpt( $block->context['postId'] );
  39. $show_more_on_new_line = ! isset( $attributes['showMoreOnNewLine'] ) || $attributes['showMoreOnNewLine'];
  40. if ( $show_more_on_new_line && ! empty( $more_text ) ) {
  41. $content .= '</p><p class="wp-block-post-excerpt__more-text">' . $more_text . '</p>';
  42. } else {
  43. $content .= " $more_text</p>";
  44. }
  45. remove_filter( 'excerpt_more', $filter_excerpt_more );
  46. return sprintf( '<div %1$s>%2$s</div>', $wrapper_attributes, $content );
  47. }
  48. /**
  49. * Registers the `core/post-excerpt` block on the server.
  50. */
  51. function register_block_core_post_excerpt() {
  52. register_block_type_from_metadata(
  53. __DIR__ . '/post-excerpt',
  54. array(
  55. 'render_callback' => 'render_block_core_post_excerpt',
  56. )
  57. );
  58. }
  59. add_action( 'init', 'register_block_core_post_excerpt' );