get_search_form()
概述
get_search_form() 函数用于在 WordPress 中显示搜索表单。它会优先加载主题中的 searchform.php 文件,如果不存在则使用默认的 HTML 表单。该函数支持通过参数和过滤器进行自定义,常用于主题侧边栏硬编码或搜索小部件。
关键要点
- 函数首先查找主题中的 searchform.php 文件,若未找到则输出默认搜索表单。
- 支持参数 $args,包括 echo(控制输出或返回)和 aria_label(用于可访问性)。
- 提供多个过滤器(如 'get_search_form'、'search_form_args')和动作(如 'pre_get_search_form')以修改表单输出。
- 默认表单根据主题是否支持 HTML5 而生成不同标记,确保兼容性。
- 常用于主题开发和小部件集成,允许通过自定义模板或函数钩子进行扩展。
代码示例
// 基本用法:输出搜索表单
get_search_form();
// 返回表单 HTML 而不输出
$form_html = get_search_form( array( 'echo' => false ) );
// 自定义搜索表单模板示例(searchform.php)
<form role="search" method="get" action="<?php echo home_url( '/' ); ?>">
<label>
<span class="screen-reader-text"><?php _x( 'Search for:', 'label' ); ?></span>
<input type="search" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ); ?>" value="<?php echo get_search_query(); ?>" name="s" />
</label>
<input type="submit" value="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" />
</form>注意事项
- 自定义 searchform.php 时,表单应使用 GET 方法提交到首页,输入字段名应为 's',并包含可访问性标签。
- 通过过滤器 'get_search_form' 可以完全替换表单 HTML,但需注意保持语义和可访问性。
- HTML5 表单使用 type="search" 和 placeholder 属性,无需 JavaScript,且支持多个表单无 ID 冲突。
- 参数 $args 在 5.2.0 版本中引入,取代了之前的 $echo 布尔参数,需注意向后兼容性处理。
Displays search form.
Description
Will first attempt to locate the searchform.php file in either the child or the parent, then load it. If it doesn’t exist, then the default search form will be displayed. The default search form is HTML, which will be displayed.
There is a filter applied to the search form HTML in order to edit or replace it. The filter is ‘get_search_form’.
This function is primarily used by themes which want to hardcode the search form into the sidebar and also by the search widget in WordPress.
There is also an action that is called whenever the function is run called, ‘pre_get_search_form’. This can be useful for outputting JavaScript that the search relies on or various formatting that applies to the beginning of the search. To give a few examples of what it can be used for.
Parameters
$argsarrayoptional-
Array of display arguments.
echoboolWhether to echo or return the form. Default true.aria_labelstringARIA label for the search form. Useful to distinguish multiple search forms on the same page and improve accessibility.
Default:
array()
Source
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 …', '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;
}
}
Hooks
- apply_filters( ‘get_search_form’, string $form, array $args )
-
Filters the HTML output of the search form.
- do_action( ‘pre_get_search_form’, array $args )
-
Fires before the search form is retrieved, at the start of get_search_form() .
- apply_filters( ‘search_form_args’, array $args )
-
Filters the array of arguments used when generating the search form.
- apply_filters( ‘search_form_format’, string $format, array $args )
-
Filters the HTML format of the search form.
Skip to note 5 content
Codex
Theme Form
If you do have
searchform.phpin your theme, it will be used instead. Keep in mind that the search form should do a GET to the homepage of your blog. The input text field should be namedsand you should always include a label like in the examples above.Example of a custom
searchform.php:<form action="/" method="get"> <label for="search">Search in </label> <input type="text" name="s" id="search" value="<?php the_search_query(); ?>" /> <input type="image" alt="Search" src="<?php bloginfo( 'template_url' ); ?>/images/search.png" /> </form>The only parameter here that will be submitted is s with the value of the current search query. However, you can refine it in many ways. For example by only showing posts in the search results. This can be done with the next addition to the form above:
<input type="hidden" value="post" name="post_type" id="post_type" />Here we submit the value post. The default value is any, meaning, posts, pages and custom post types. With the input above added to the form it will now only search in posts with the
post_typepost. There are many additions like this. With avar_dumpof the object$wp_queryyou can see all the default values of the search variables. With avar_dumpof$wp_query->queryyou can see the current query.A last option is to write a custom function (in your
functions.phpfile) and hook that function to theget_search_formaction hook./** * Generate custom search form * * @param string $form Form HTML. * @return string Modified form HTML. */ function wpdocs_my_search_form( $form ) { $form = '<form role="search" method="get" id="searchform" class="searchform" action="' . home_url( '/' ) . '" > <div><label class="screen-reader-text" for="s">' . __( 'Search for:' ) . '</label> <input type="text" value="' . get_search_query() . '" name="s" id="s" /> <input type="submit" id="searchsubmit" value="'. esc_attr__( 'Search' ) .'" /> </div> </form>'; return $form; } add_filter( 'get_search_form', 'wpdocs_my_search_form' );Skip to note 6 content
Codex
Default HTML5 Form
Since WordPress 3.6, If your theme supports HTML5 Markup, which happens if it uses:
/** * Add HTML5 theme support. */ function wpdocs_after_setup_theme() { add_theme_support( 'html5', array( 'search-form' ) ); } add_action( 'after_setup_theme', 'wpdocs_after_setup_theme' );WordPress will render its built-in HTML5 search form:
<form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>"> <label> <span class="screen-reader-text"></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>Among the changes is that the form has a
class="search-form". Also, the input istype="search"and nottype="text". Furthermore there is a placeholder, which displays text when appropriate, which means you don’t need JavaScript to display the placeholder. There are no elements with an id anymore, so you can have multiple searchforms in a valid document.Skip to note 7 content
Codex
Default HTML4 Form
If you don’t have
searchform.phpin your theme, WordPress will render its built-in search form:<form role="search" method="get" id="searchform" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>"> <div> <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="<?php echo esc_attr_x( 'Search', 'submit button' ); ?>" /> </div> </form>The above form is used on HTML4 websites.
Skip to note 8 content
Deafinitive
[html]
<form role="search"
[/html]
This is incorrect as it overrides the native semantics of the element.
Place
role="search"before or after the <form element[html]
<form method="get" id="searchform" class="searchform" …
<div role="search"
[/html]
or
[html]
<div role="search"
<form method="get" id="searchform" class="searchform" …
[/html]