post-date.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. /**
  3. * Server-side rendering of the `core/post-date` block.
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Renders the `core/post-date` 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 date for the current post wrapped inside "time" tags.
  14. */
  15. function render_block_core_post_date( $attributes, $content, $block ) {
  16. if ( ! isset( $block->context['postId'] ) ) {
  17. return '';
  18. }
  19. $post_ID = $block->context['postId'];
  20. $align_class_name = empty( $attributes['textAlign'] ) ? '' : "has-text-align-{$attributes['textAlign']}";
  21. $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => $align_class_name ) );
  22. if ( isset( $attributes['displayType'] ) && 'modified' === $attributes['displayType'] ) {
  23. $formatted_date = get_the_modified_date( empty( $attributes['format'] ) ? '' : $attributes['format'], $post_ID );
  24. $unformatted_date = esc_attr( get_the_modified_date( 'c', $post_ID ) );
  25. } else {
  26. $formatted_date = get_the_date( empty( $attributes['format'] ) ? '' : $attributes['format'], $post_ID );
  27. $unformatted_date = esc_attr( get_the_date( 'c', $post_ID ) );
  28. }
  29. if ( isset( $attributes['isLink'] ) && $attributes['isLink'] ) {
  30. $formatted_date = sprintf( '<a href="%1s">%2s</a>', get_the_permalink( $post_ID ), $formatted_date );
  31. }
  32. return sprintf(
  33. '<div %1$s><time datetime="%2$s">%3$s</time></div>',
  34. $wrapper_attributes,
  35. $unformatted_date,
  36. $formatted_date
  37. );
  38. }
  39. /**
  40. * Registers the `core/post-date` block on the server.
  41. */
  42. function register_block_core_post_date() {
  43. register_block_type_from_metadata(
  44. __DIR__ . '/post-date',
  45. array(
  46. 'render_callback' => 'render_block_core_post_date',
  47. )
  48. );
  49. }
  50. add_action( 'init', 'register_block_core_post_date' );