函数文档

is_single()

💡 云策文档标注

概述

is_single() 是 WordPress 的条件标签函数,用于判断当前查询是否为单个文章页面。它适用于除附件和页面外的所有文章类型,并可指定文章参数进行精确检查。

关键要点

  • 用于检测当前查询是否为单个文章页面,返回布尔值。
  • 支持可选参数 $post,可传入文章 ID、标题、slug 或数组来匹配特定文章。
  • 不适用于附件和页面类型,建议使用 is_attachment() 或 is_singular() 处理这些情况。
  • 函数内部调用 WP_Query::is_single(),需在查询运行后使用,否则会触发 _doing_it_wrong() 警告。

代码示例

// 检查是否为任何单个文章页面
if ( is_single() ) {
    // 执行代码
}

// 检查是否为特定文章(ID 17)
if ( is_single(17) ) {
    // 执行代码
}

// 检查是否为特定文章(slug 'beef-stew')
if ( is_single('beef-stew') ) {
    // 执行代码
}

// 检查是否为多个文章之一(数组参数)
if ( is_single(array(17, 'beef-stew', 'Irish Stew')) ) {
    // 执行代码
}

注意事项

  • is_single() 通常对附件返回 true,但不应依赖此行为,因为 $is_page 和 $is_attachment 可能同时为 true,导致 $is_single 为 false。
  • 如需包含附件,建议使用 is_attachment() || is_single();如需包含页面,使用 is_singular()。
  • 函数在 WordPress 1.5.0 版本引入,数组参数支持从 2.5 版本开始。

📄 原文内容

Determines whether the query is for an existing single post.

Description

Works for any post type, except attachments and pages

If the $post parameter is specified, this function will additionally check if the query is for one of the Posts specified.

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

See also

Parameters

$postint|string|int[]|string[]optional
Post ID, title, slug, or array of such to check against. Default empty.

Return

bool Whether the query is for an existing single post.

More Information

  • See Also: is_singular()
  • Although is_single() will usually return true for attachments, this behavior should not be relied upon. It is possible for $is_page and $is_attachment to be true at the same time, and in that case $is_single will be false. For this reason, you should use is_attachment() || is_single() if you want to include attachments, or use is_singular() if you want to include pages too.

Source

function is_single( $post = '' ) {
	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_single( $post );
}

Changelog

Version Description
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 6 content

    is_single();
    // When any single Post page is being displayed.
    
    is_single('17');
    // When Post 17 (ID) is being displayed.
    
    is_single(17);
    // When Post 17 (ID) is being displayed. Integer parameter also works
    is_single('Irish Stew');
    // When the Post with post_title of "Irish Stew" is being displayed.
    
    is_single('beef-stew');
    // When the Post with post_name (slug) of "beef-stew" is being displayed.
    
    is_single(array(17,'beef-stew','Irish Stew'));
    // Returns true when the single post being displayed is either post ID 17,
    // or the post_name is "beef-stew", or the post_title is "Irish Stew".
    // Note: the array ability was added in version 2.5.