is_404()
云策文档标注
概述
is_404() 是 WordPress 中的一个条件标签函数,用于判断当前查询是否返回了 404 错误(即无结果)。它检查全局 $wp_query 对象的状态,返回布尔值。
关键要点
- is_404() 返回布尔值,表示查询是否为 404 错误。
- 函数依赖于全局 $wp_query 对象,在查询运行前调用会返回 false 并触发 _doing_it_wrong() 警告。
- 常用于主题开发中,根据 404 状态定制页面内容或添加功能。
- 相关函数包括 WP_Query::is_404()、__() 和 _doing_it_wrong(),并在多个核心函数中被使用。
代码示例
if ( is_404() ) {
// add search form so that users can search other posts
}注意事项
is_404() 必须在查询运行后调用,否则会返回 false 并可能产生错误提示。建议在适当的钩子(如 'wp')中使用以确保查询已初始化。
原文内容
Determines whether the query has resulted in a 404 (returns no results).
Description
For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.
Source
function is_404() {
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_404();
}
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 3 content
Codex
Example
if ( is_404() ) { // add search form so that users can search other posts }Skip to note 4 content
Usman Ahmed
Add this function in a hook. I normally use
'wp'for this.add_action ( 'wp', function() { if (is_404()) { // Your Code Here } } );