is_month()
云策文档标注
概述
is_month() 是 WordPress 中的一个条件标签函数,用于判断当前查询是否为现有月份归档页面。它依赖于全局 $wp_query 对象,在查询运行前调用会返回 false 并触发警告。
关键要点
- is_month() 返回布尔值,指示查询是否针对现有月份归档。
- 函数内部调用 $wp_query->is_month(),需确保查询已运行,否则会触发 _doing_it_wrong() 警告。
- 常用于主题开发中,结合其他条件标签进行页面逻辑控制。
- 相关函数包括 WP_Query::is_month()、__() 和 _doing_it_wrong(),用于查询、翻译和错误处理。
- 自 WordPress 1.5.0 版本引入,稳定用于归档标题生成和规范重定向等场景。
代码示例
if ( is_month() ) {
// 执行月份归档相关操作。
}注意事项
- 在查询运行前调用 is_month() 会始终返回 false,并可能输出错误信息,影响性能或调试。
- 建议在模板文件或钩子函数中确保查询已初始化后再使用此函数。
原文内容
Determines whether the query is for an existing month archive.
Description
For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.
Source
function is_month() {
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_month();
}
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 2 content
Codex
Check if current archive is month archive.
if ( is_month() ) { // Do awesome. }