暫無描述

post-title.php 1.6KB

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. $title = sprintf( '<a href="%1$s" target="%2$s" rel="%3$s">%4$s</a>', get_the_permalink( $post_ID ), esc_attr( $attributes['linkTarget'] ), esc_attr( $attributes['rel'] ), $title );
  32. }
  33. $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => $align_class_name ) );
  34. return sprintf(
  35. '<%1$s %2$s>%3$s</%1$s>',
  36. $tag_name,
  37. $wrapper_attributes,
  38. $title
  39. );
  40. }
  41. /**
  42. * Registers the `core/post-title` block on the server.
  43. */
  44. function register_block_core_post_title() {
  45. register_block_type_from_metadata(
  46. __DIR__ . '/post-title',
  47. array(
  48. 'render_callback' => 'render_block_core_post_title',
  49. )
  50. );
  51. }
  52. add_action( 'init', 'register_block_core_post_title' );