get_search_query()
云策文档标注
概述
get_search_query() 函数用于检索 WordPress 搜索查询变量的内容,并可选地通过 esc_attr() 进行转义以确保 HTML 属性安全。
关键要点
- 函数检索查询变量 's' 的值,即搜索查询字符串。
- 参数 $escaped 控制是否对结果进行转义,默认值为 true,适用于直接输出到 HTML 属性的场景。
- 通过 apply_filters('get_search_query', $search) Hook 允许过滤搜索查询内容。
- 返回类型为字符串,转义时使用 esc_attr() 函数。
代码示例
function get_search_query( $escaped = true ) {
$query = apply_filters( 'get_search_query', get_query_var( 's' ) );
if ( $escaped ) {
$query = esc_attr( $query );
}
return $query;
}注意事项
- 仅在后续需要转义时使用未转义的参数,避免安全风险。
- 相关函数包括 get_query_var()、esc_attr() 和 apply_filters()。
- 自 WordPress 2.3.0 版本引入。
原文内容
Retrieves the contents of the search WordPress query variable.
Description
The search query string is passed through esc_attr() to ensure that it is safe for placing in an HTML attribute.
Parameters
$escapedbooloptional-
Whether the result is escaped.
Only use when you are later escaping it. Do not use unescaped.Default:
true
Source
function get_search_query( $escaped = true ) {
/**
* Filters the contents of the search query variable.
*
* @since 2.3.0
*
* @param mixed $search Contents of the search query variable.
*/
$query = apply_filters( 'get_search_query', get_query_var( 's' ) );
if ( $escaped ) {
$query = esc_attr( $query );
}
return $query;
}
Hooks
- apply_filters( ‘get_search_query’, mixed $search )
-
Filters the contents of the search query variable.
Changelog
| Version | Description |
|---|---|
| 2.3.0 | Introduced. |
Skip to note 2 content
Codex
Different usage methods