# get_search_form()

URL: https://chugunov.pro/api-wordpress/functions/get_search_form/
Проверено на WordPress 6.9, обновлено 06.08.2026.
Источник: независимый русскоязычный справочник chugunov.pro. Не является официальной документацией WordPress.

Тип: функция.
Появился в версии: 2.7.0.

## Сигнатура

```php
get_search_form( array $args = array() ): void|string
```

## Описание

Сначала пытается найти файл searchform.php в дочерней или родительской теме, а затем загружает его. Если он не существует, отображается форма поиска по умолчанию. Форма поиска по умолчанию представляет собой HTML, который и выводится.
К HTML формы поиска применяется фильтр, позволяющий отредактировать или заменить её. Это фильтр ‘get_search_form’.
Эта функция в основном используется темами, которые хотят жёстко встроить форму поиска в боковую панель, а также виджетом поиска в WordPress.
Кроме того, при каждом запуске функции вызывается действие ‘pre_get_search_form’. Оно может пригодиться для вывода JavaScript, от которого зависит поиск, или различного форматирования в начале поиска — вот лишь несколько примеров его применения.

## Параметры

- `$args` `array` — необязательный, по умолчанию `array()`. Массив аргументов вывода.
  
  echo boolВыводить форму или возвращать её. Значение по умолчанию true.
  
  aria_label stringARIA-метка для формы поиска. Полезна для различения нескольких форм поиска на одной странице и улучшения доступности.

## Возвращаемое значение

`void|string` — 'echo' 'echo'

## Исходный код

Файл: `wp-includes/general-template.php:241`

```php
function get_search_form( $args = array() ) {
	/**
	 * Fires before the search form is retrieved, at the start of get_search_form().
	 *
	 * @since 2.7.0 as 'get_search_form' action.
	 * @since 3.6.0
	 * @since 5.5.0 The `$args` parameter was added.
	 *
	 * @link https://core.trac.wordpress.org/ticket/19321
	 *
	 * @param array $args The array of arguments for building the search form.
	 *                    See get_search_form() for information on accepted arguments.
	 */
	do_action( 'pre_get_search_form', $args );

	$echo = true;

	if ( ! is_array( $args ) ) {
		/*
		 * Back compat: to ensure previous uses of get_search_form() continue to
		 * function as expected, we handle a value for the boolean $echo param removed
		 * in 5.2.0. Then we deal with the $args array and cast its defaults.
		 */
		$echo = (bool) $args;

		// Set an empty array and allow default arguments to take over.
		$args = array();
	}

	// Defaults are to echo and to output no custom label on the form.
	$defaults = array(
		'echo'       => $echo,
		'aria_label' => '',
	);

	$args = wp_parse_args( $args, $defaults );

	/**
	 * Filters the array of arguments used when generating the search form.
	 *
	 * @since 5.2.0
	 *
	 * @param array $args The array of arguments for building the search form.
	 *                    See get_search_form() for information on accepted arguments.
	 */
	$args = apply_filters( 'search_form_args', $args );

	// Ensure that the filtered arguments contain all required default values.
	$args = array_merge( $defaults, $args );

	$format = current_theme_supports( 'html5', 'search-form' ) ? 'html5' : 'xhtml';

	/**
	 * Filters the HTML format of the search form.
	 *
	 * @since 3.6.0
	 * @since 5.5.0 The `$args` parameter was added.
	 *
	 * @param string $format The type of markup to use in the search form.
	 *                       Accepts 'html5', 'xhtml'.
	 * @param array  $args   The array of arguments for building the search form.
	 *                       See get_search_form() for information on accepted arguments.
	 */
	$format = apply_filters( 'search_form_format', $format, $args );

	$search_form_template = locate_template( 'searchform.php' );

	if ( '' !== $search_form_template ) {
		ob_start();
		require $search_form_template;
		$form = ob_get_clean();
	} else {
		// Build a string containing an aria-label to use for the search form.
		if ( $args['aria_label'] ) {
			$aria_label = 'aria-label="' . esc_attr( $args['aria_label'] ) . '" ';
		} else {
			/*
			 * If there's no custom aria-label, we can set a default here. At the
			 * moment it's empty as there's uncertainty about what the default should be.
			 */
			$aria_label = '';
		}

		if ( 'html5' === $format ) {
			$form = '<form role="search" ' . $aria_label . 'method="get" class="search-form" action="' . esc_url( home_url( '/' ) ) . '">
				<label>
					<span class="screen-reader-text">' .
					/* translators: Hidden accessibility text. */
					_x( 'Search for:', 'label' ) .
					'</span>
					<input type="search" class="search-field" placeholder="' . esc_attr_x( 'Search &hellip;', 'placeholder' ) . '" value="' . get_search_query() . '" name="s" />
				</label>
				<input type="submit" class="search-submit" value="' . esc_attr_x( 'Search', 'submit button' ) . '" />
			</form>';
		} else {
			$form = '<form role="search" ' . $aria_label . 'method="get" id="searchform" class="searchform" action="' . esc_url( home_url( '/' ) ) . '">
				<div>
					<label class="screen-reader-text" for="s">' .
					/* translators: Hidden accessibility text. */
					_x( 'Search for:', 'label' ) .
					'</label>
					<input type="text" value="' . get_search_query() . '" name="s" id="s" />
					<input type="submit" id="searchsubmit" value="' . esc_attr_x( 'Search', 'submit button' ) . '" />
				</div>
			</form>';
		}
	}

	/**
	 * Filters the HTML output of the search form.
	 *
	 * @since 2.7.0
	 * @since 5.5.0 The `$args` parameter was added.
	 *
	 * @param string $form The search form HTML output.
	 * @param array  $args The array of arguments for building the search form.
	 *                     See get_search_form() for information on accepted arguments.
	 */
	$result = apply_filters( 'get_search_form', $form, $args );

	if ( null === $result ) {
		$result = $form;
	}

	if ( $args['echo'] ) {
		echo $result;
	} else {
		return $result;
	}
}
```

## История изменений

- 5.2.0 — The $args array parameter was added in place of an $echo boolean flag.
- 2.7.0 — Introduced.

## Связанные

Использует: [`esc_attr_x`](https://chugunov.pro/api-wordpress/functions/esc_attr_x/), [`get_search_query`](https://chugunov.pro/api-wordpress/functions/get_search_query/), [`locate_template`](https://chugunov.pro/api-wordpress/functions/locate_template/), [`current_theme_supports`](https://chugunov.pro/api-wordpress/functions/current_theme_supports/), [`_x`](https://chugunov.pro/api-wordpress/functions/_x/), [`esc_attr`](https://chugunov.pro/api-wordpress/functions/esc_attr/), [`esc_url`](https://chugunov.pro/api-wordpress/functions/esc_url/), [`wp_parse_args`](https://chugunov.pro/api-wordpress/functions/wp_parse_args/), [`home_url`](https://chugunov.pro/api-wordpress/functions/home_url/), [`do_action`](https://chugunov.pro/api-wordpress/functions/do_action/), [`apply_filters`](https://chugunov.pro/api-wordpress/functions/apply_filters/).
Используется в: `WP_Widget_Search::widget`.

Оригинал в официальной документации: https://developer.wordpress.org/reference/functions/get_search_form/
