cover.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * Server-side rendering of the `core/cover` block.
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Renders the `core/cover` block on server.
  9. *
  10. * @param array $attributes The block attributes.
  11. * @param string $content The block rendered content.
  12. *
  13. * @return string Returns the cover block markup, if useFeaturedImage is true.
  14. */
  15. function render_block_core_cover( $attributes, $content ) {
  16. if ( 'image' !== $attributes['backgroundType'] || false === $attributes['useFeaturedImage'] ) {
  17. return $content;
  18. }
  19. if ( ! ( $attributes['hasParallax'] || $attributes['isRepeated'] ) ) {
  20. $attr = array(
  21. 'class' => 'wp-block-cover__image-background',
  22. 'data-object-fit' => 'cover',
  23. );
  24. if ( isset( $attributes['focalPoint'] ) ) {
  25. $object_position = round( $attributes['focalPoint']['x'] * 100 ) . '%' . ' ' . round( $attributes['focalPoint']['y'] * 100 ) . '%';
  26. $attr['data-object-position'] = $object_position;
  27. $attr['style'] = 'object-position: ' . $object_position;
  28. }
  29. $image = get_the_post_thumbnail( null, 'post-thumbnail', $attr );
  30. /*
  31. * Inserts the featured image between the (1st) cover 'background' `span` and 'inner_container' `div`,
  32. * and removes eventual withespace characters between the two (typically introduced at template level)
  33. */
  34. $inner_container_start = '/<div\b[^>]+wp-block-cover__inner-container[\s|"][^>]*>/U';
  35. if ( 1 === preg_match( $inner_container_start, $content, $matches, PREG_OFFSET_CAPTURE ) ) {
  36. $offset = $matches[0][1];
  37. $content = substr( $content, 0, $offset ) . $image . substr( $content, $offset );
  38. }
  39. } else {
  40. if ( in_the_loop() ) {
  41. update_post_thumbnail_cache();
  42. }
  43. $current_featured_image = get_the_post_thumbnail_url();
  44. $styles = 'background-image:url(' . esc_url( $current_featured_image ) . '); ';
  45. if ( isset( $attributes['minHeight'] ) ) {
  46. $height_unit = empty( $attributes['minHeightUnit'] ) ? 'px' : $attributes['minHeightUnit'];
  47. $height = " min-height:{$attributes['minHeight']}{$height_unit}";
  48. $styles .= $height;
  49. }
  50. $content = preg_replace(
  51. '/class=\".*?\"/',
  52. '${0} style="' . $styles . '"',
  53. $content,
  54. 1
  55. );
  56. }
  57. return $content;
  58. }
  59. /**
  60. * Registers the `core/cover` block renderer on server.
  61. */
  62. function register_block_core_cover() {
  63. register_block_type_from_metadata(
  64. __DIR__ . '/cover',
  65. array(
  66. 'render_callback' => 'render_block_core_cover',
  67. )
  68. );
  69. }
  70. add_action( 'init', 'register_block_core_cover' );