WordPress как на ладони
rgbcode is looking for WordPress developers.

get_search_form()WP 2.7.0

Подключает форму поиска, файл темы searchform.php. Если такого файла в шаблоне темы нет, то будет использован дефолтный код для формы поиска.

Не забывайте про безопасность

В строку поиска, пользователь может вписать что угодно, например рабочий скрипт <script>alert('aaaa');<script>. И если вывести строку запроса на странице как есть, то такой скрипт будет обработан браузером. А если в него написать что-то нехорошее, то ваш сайт можно будет легко взломать.

Поэтому для вывода запроса поиска на экран, всегда используйте функцию get_search_query(). Она обезопасит вас от XSS атак. Именно это место является одним из самых слабых в безопасности самодельных WordPress тем.

<?php echo get_search_query(); ?>

Выводимую строку также можно очистить с помощью: esc_attr(), esc_html().

Возвращает

null|Строку.

Использование

<?php get_search_form( $args ); ?>
$args(true/false/array)

C версии 5.2 параметр превратился в массив аргументов:

  • echo(true/false)
    Нужно ли выводить созданные HTML код на экран.
    По умолчанию: true

  • aria_label(строка)
    Значение артирбута <form aria-label="XXX">. Будет полезен, чтобы отличать несколько форм на одной странице.
    По умолчанию: ''

До версии 5.2 параметр назывался $echo, был логическим и отвечал за вывод HTML на экран:

  • true — Выводить код на экран.
  • false — возвращать для обработки.

По умолчанию: array()

Примеры

7

#1 HTML формы поиска через файл searchform.php

Создаем файл searchform.php в папке темы с кодом:

<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ) ?>" >
	<label class="screen-reader-text" for="s">Поиск: </label>
	<input type="text" value="<?php echo get_search_query() ?>" name="s" id="s" />
	<input type="submit" id="searchsubmit" value="найти" />
</form>

Затем, там где нужна форма поиска, вызываем функцию get_search_form(), которая выведет содержимое созданного нами файла searchform.php:

<?php get_search_form(); ?>

Имейте ввиду, что форма поиска должна отправлять GET запрос на главную страницу сайта: action="<?php echo home_url( '/' ); ?>") и обязательно должен присутствовать параметр s (что искать): <input type="text" value="" name="s" id="s" />.

4

#2 HTML формы поиска через хук

Можно не создавать файл темы searchform.php, а изменить HTML код формы через хук get_search_form, который нужно вставлять в файл темы functions.php.

add_filter( 'get_search_form', 'my_search_form' );
function my_search_form( $form ) {

	$form = '
	<form role="search" method="get" id="searchform" action="' . home_url( '/' ) . '" >
		<label class="screen-reader-text" for="s">Запрос для поиска:</label>
		<input type="text" value="' . get_search_query() . '" name="s" id="s" />
		<input type="submit" id="searchsubmit" value="Найти" />
	</form>';

	return $form;
}
3

#3 Фильтр (ограничение) результатов поиска

Кроме параметра запроса s, можно отфильтровать поиск по типу записи. Для этого добавьте в форму еще одно input поле с именем post_type:

<input type="hidden" value="post" name="post_type" />

В результате при отправке формы (сабмите) мы получит строку запроса вида: ?s=текст&post_type=post. А это значит, что поиск будет проходить не по всем типам записей, а только по типу записи указанному в поле name="post_type", в данном случае по типу post. По умолчанию там указано: post_type = any (любой тип записи).

Также результаты поиска можно отфильтровать как угодно, используя событие pre_get_posts. Примеры смотрите в описании.

2

#4 HTML формы поиска по умолчанию

Если в теме нет файла searchform.php, то вызов этой функции выведет HTML формы по умолчанию:

<form role="search" method="get" id="searchform" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
	<div>
		<label class="screen-reader-text" for="s"><?php _x( 'Search for:', 'label' ); ?></label>
		<input type="text" value="<?php echo get_search_query(); ?>" name="s" id="s" />
		<input type="submit" id="searchsubmit" value="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" />
	</div>
</form>

Такая HTML разметка будет выведена если, НЕ установлена поддержка html5 в теме. Напомню, устанавливается она через функцию add_theme_support() так:

add_theme_support( 'html5', array( 'search-form' ) );

Однако, если поддержка html5 включена, то по умолчанию мы получим такой HTML код формы поиска:

<form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
	<label>
		<span class="screen-reader-text"><?php echo _x( 'Search for:', 'label' ) ?></span>
		<input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
	</label>
	<input type="submit" class="search-submit" value="<?php echo esc_attr_x( 'Search', 'submit button' ) ?>" />
</form>

То есть тип поля меняется с text на search: type="search".

Предпочтение стоит отдавать html5 форме, поэтому всегда включайте эту настройку в темах!

Список изменений

С версии 2.7.0 Введена.
С версии 5.2.0 The $args array parameter was added in place of an $echo boolean flag.

Код get_search_form() WP 6.4.3

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;
	}
}
35 комментариев
Полезные 2Вопросы 1 Все
    Войти