is_attachment()
云策文档标注
概述
is_attachment() 是一个 WordPress 条件标签函数,用于判断当前查询是否为现有附件页面。它基于全局 $wp_query 对象,并支持可选参数进行更精确的检查。
关键要点
- 函数用于检查查询是否为附件页面,返回布尔值。
- 接受可选参数 $attachment,可以是附件 ID、标题、slug 或数组,用于特定附件匹配。
- 在查询运行前调用会触发 _doing_it_wrong() 警告并返回 false。
- 内部调用 WP_Query::is_attachment() 方法实现功能。
代码示例
if ( is_attachment() ) {
// 当前页面是附件页面时的代码
}注意事项
- 使用前需确保查询已运行,否则可能返回错误结果。
- 相关函数包括 is_singular() 用于更通用的单页面检查,wp_attachment_is_image() 用于检查附件是否为图像。
原文内容
Determines whether the query is for an existing attachment page.
Description
For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.
Parameters
$attachmentint|string|int[]|string[]optional-
Attachment ID, title, slug, or array of such to check against. Default empty.
Source
function is_attachment( $attachment = '' ) {
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_attachment( $attachment );
}
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |
Skip to note 2 content
Codex
Basic Example
?>