query-title.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Server-side rendering of the `core/query-title` block.
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Renders the `core/query-title` block on the server.
  9. * For now it only supports Archive title,
  10. * using queried object information
  11. *
  12. * @param array $attributes Block attributes.
  13. *
  14. * @return string Returns the query title based on the queried object.
  15. */
  16. function render_block_core_query_title( $attributes ) {
  17. $type = isset( $attributes['type'] ) ? $attributes['type'] : null;
  18. $is_archive = is_archive();
  19. $is_search = is_search();
  20. if ( ! $type ||
  21. ( 'archive' === $type && ! $is_archive ) ||
  22. ( 'search' === $type && ! $is_search )
  23. ) {
  24. return '';
  25. }
  26. $title = '';
  27. if ( $is_archive ) {
  28. $show_prefix = isset( $attributes['showPrefix'] ) ? $attributes['showPrefix'] : true;
  29. if ( ! $show_prefix ) {
  30. $filter_title = function( $title, $original_title ) {
  31. return $original_title;
  32. };
  33. add_filter( 'get_the_archive_title', $filter_title, 10, 2 );
  34. $title = get_the_archive_title();
  35. remove_filter( 'get_the_archive_title', $filter_title, 10, 2 );
  36. } else {
  37. $title = get_the_archive_title();
  38. }
  39. }
  40. if ( $is_search ) {
  41. $title = __( 'Search results' );
  42. if ( isset( $attributes['showSearchTerm'] ) && $attributes['showSearchTerm'] ) {
  43. $title = sprintf(
  44. /* translators: %s is the search term. */
  45. __( 'Search results for: "%s"' ),
  46. get_search_query()
  47. );
  48. }
  49. }
  50. $tag_name = isset( $attributes['level'] ) ? 'h' . (int) $attributes['level'] : 'h1';
  51. $align_class_name = empty( $attributes['textAlign'] ) ? '' : "has-text-align-{$attributes['textAlign']}";
  52. $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => $align_class_name ) );
  53. return sprintf(
  54. '<%1$s %2$s>%3$s</%1$s>',
  55. $tag_name,
  56. $wrapper_attributes,
  57. $title
  58. );
  59. }
  60. /**
  61. * Registers the `core/query-title` block on the server.
  62. */
  63. function register_block_core_query_title() {
  64. register_block_type_from_metadata(
  65. __DIR__ . '/query-title',
  66. array(
  67. 'render_callback' => 'render_block_core_query_title',
  68. )
  69. );
  70. }
  71. add_action( 'init', 'register_block_core_query_title' );