post-title.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * Server-side rendering of the `core/post-title` block.
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Renders the `core/post-title` 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. *
  14. * @return string Returns the filtered post title for the current post wrapped inside "h1" tags.
  15. */
  16. function render_block_core_post_title( $attributes, $content, $block ) {
  17. if ( ! isset( $block->context['postId'] ) ) {
  18. return '';
  19. }
  20. $post_ID = $block->context['postId'];
  21. $title = get_the_title();
  22. if ( ! $title ) {
  23. return '';
  24. }
  25. $tag_name = 'h2';
  26. $align_class_name = empty( $attributes['textAlign'] ) ? '' : "has-text-align-{$attributes['textAlign']}";
  27. if ( isset( $attributes['level'] ) ) {
  28. $tag_name = 0 === $attributes['level'] ? 'p' : 'h' . $attributes['level'];
  29. }
  30. if ( isset( $attributes['isLink'] ) && $attributes['isLink'] ) {
  31. $rel = ! empty( $attributes['rel'] ) ? 'rel="' . esc_attr( $attributes['rel'] ) . '"' : '';
  32. $title = sprintf( '<a href="%1$s" target="%2$s" %3$s>%4$s</a>', get_the_permalink( $post_ID ), esc_attr( $attributes['linkTarget'] ), $rel, $title );
  33. }
  34. $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => $align_class_name ) );
  35. return sprintf(
  36. '<%1$s %2$s>%3$s</%1$s>',
  37. $tag_name,
  38. $wrapper_attributes,
  39. $title
  40. );
  41. }
  42. /**
  43. * Registers the `core/post-title` block on the server.
  44. */
  45. function register_block_core_post_title() {
  46. register_block_type_from_metadata(
  47. __DIR__ . '/post-title',
  48. array(
  49. 'render_callback' => 'render_block_core_post_title',
  50. )
  51. );
  52. }
  53. add_action( 'init', 'register_block_core_post_title' );