search.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * Server-side rendering of the `core/search` block.
  4. *
  5. * @package WordPress
  6. */
  7. /**
  8. * Dynamically renders the `core/search` block.
  9. *
  10. * @param array $attributes The block attributes.
  11. *
  12. * @return string The search block markup.
  13. */
  14. function render_block_core_search( $attributes ) {
  15. static $instance_id = 0;
  16. $input_id = 'wp-block-search__input-' . ++$instance_id;
  17. $label_markup = '';
  18. $button_markup = '';
  19. if ( ! empty( $attributes['label'] ) ) {
  20. $label_markup = sprintf(
  21. '<label for="%s" class="wp-block-search__label">%s</label>',
  22. $input_id,
  23. $attributes['label']
  24. );
  25. }
  26. $input_markup = sprintf(
  27. '<input type="search" id="%s" class="wp-block-search__input" name="s" value="%s" placeholder="%s" />',
  28. $input_id,
  29. esc_attr( get_search_query() ),
  30. esc_attr( $attributes['placeholder'] )
  31. );
  32. if ( ! empty( $attributes['buttonText'] ) ) {
  33. $button_markup = sprintf(
  34. '<button type="submit" class="wp-block-search__button">%s</button>',
  35. $attributes['buttonText']
  36. );
  37. }
  38. $class = 'wp-block-search';
  39. if ( isset( $attributes['className'] ) ) {
  40. $class .= ' ' . $attributes['className'];
  41. }
  42. if ( isset( $attributes['align'] ) ) {
  43. $class .= ' align' . $attributes['align'];
  44. }
  45. return sprintf(
  46. '<form class="%s" role="search" method="get" action="%s">%s</form>',
  47. $class,
  48. esc_url( home_url( '/' ) ),
  49. $label_markup . $input_markup . $button_markup
  50. );
  51. }
  52. /**
  53. * Registers the `core/search` block on the server.
  54. */
  55. function register_block_core_search() {
  56. register_block_type(
  57. 'core/search',
  58. array(
  59. 'attributes' => array(
  60. 'align' => array(
  61. 'type' => 'string',
  62. 'enum' => array( 'left', 'center', 'right', 'wide', 'full' ),
  63. ),
  64. 'className' => array(
  65. 'type' => 'string',
  66. ),
  67. 'label' => array(
  68. 'type' => 'string',
  69. 'default' => __( 'Search' ),
  70. ),
  71. 'placeholder' => array(
  72. 'type' => 'string',
  73. 'default' => '',
  74. ),
  75. 'buttonText' => array(
  76. 'type' => 'string',
  77. 'default' => __( 'Search' ),
  78. ),
  79. ),
  80. 'render_callback' => 'render_block_core_search',
  81. )
  82. );
  83. }
  84. add_action( 'init', 'register_block_core_search' );