函数文档

is_search()

💡 云策文档标注

概述

is_search() 是一个 WordPress 条件标签函数,用于判断当前查询是否为搜索查询。它返回布尔值,通常在主题开发中用于条件逻辑处理。

关键要点

  • 函数返回布尔值,表示查询是否为搜索
  • 依赖于全局 $wp_query 对象,查询运行前调用会返回 false 并触发 _doing_it_wrong() 警告
  • 常用于主题模板中,根据搜索状态执行特定代码
  • 相关函数包括 WP_Query::is_search(),用于更底层的查询判断

代码示例

if ( is_search() ) {
    // add external search form (Google, Yahoo, Bing...)
}
if ( is_search() ) {
    echo 'Search for: ' . esc_html( $_GET['s'] );
}

注意事项

在查询运行前调用 is_search() 会返回 false 并可能产生错误提示,应确保在适当时机使用。


📄 原文内容

Determines whether the query is for a search.

Description

For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.

Return

bool Whether the query is for a search.

Source

function is_search() {
	global $wp_query;

	if ( ! isset( $wp_query ) ) {
		_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
		return false;
	}

	return $wp_query->is_search();
}

Changelog

Version Description
1.5.0 Introduced.

User Contributed Notes