函数文档

is_singular()

💡 云策文档标注

概述

is_singular() 是一个 WordPress 条件标签函数,用于判断当前查询是否为任何文章类型的单个现有文章,包括文章、附件、页面和自定义文章类型。它基于全局 $wp_query 对象工作,并可接受 $post_types 参数来指定检查的文章类型。

关键要点

  • is_singular() 检查查询是否为单个现有文章,涵盖所有文章类型(如 post、attachment、page 和自定义文章类型)。
  • 可选参数 $post_types 允许指定一个文章类型或数组,以进一步限制检查范围。
  • 函数内部调用 WP_Query::is_singular(),如果 $wp_query 未设置,会触发 _doing_it_wrong() 并返回 false。
  • 相关函数包括 is_page() 和 is_single(),用于更具体的查询检查。
  • 在主题开发中常用于条件逻辑,例如显示不同的侧边栏广告或内容。

代码示例

// 检查是否为任何单个文章
if ( is_singular() ) {
    // 显示广告 #1
} else {
    // 显示广告 #2
}

// 检查是否为特定文章类型
if ( is_singular( 'post' ) ) {
    // 针对常规文章的代码
}

// 检查是否为多个自定义文章类型
if ( is_singular( array( 'newspaper', 'book' ) ) ) {
    // 针对报纸或书籍文章的代码
}

// 在钩子函数中使用
add_action( 'loop_start', 'your_function' );
function your_function() {
    if ( is_singular() ) {
        echo 'Hello World';
    }
}

注意事项

  • is_singular() 在查询运行前无效,会返回 false 并可能触发警告。
  • 当使用静态页面作为首页时,is_singular() 和 is_page() 可能返回 true,但在博客页面返回 false。
  • 确保在适当的钩子(如 loop_start)中使用,以避免条件标签过早执行。

📄 原文内容

Determines whether the query is for an existing single post of any post type (post, attachment, page, custom post types).

Description

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

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

See also

Parameters

$post_typesstring|string[]optional
Post type or array of post types to check against. Default empty.

Return

bool Whether the query is for an existing single post or any of the given post types.

Source

function is_singular( $post_types = '' ) {
	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_singular( $post_types );
}

Changelog

Version Description
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 8 content

    Custom Post Types

    When any of the following return true: is_single() , is_page() or is_attachment() .

    is_singular();

    True when viewing a post of the Custom Post Type book.

    is_singular( 'book' );

    True when viewing a post of the Custom Post Type newspaper or book.

    is_singular( array( 'newspaper', 'book' ) );