函数文档

is_tag()

💡 云策文档标注

概述

is_tag() 是一个 WordPress 条件标签函数,用于判断当前查询是否为标签存档页面。它可接受可选参数来检查特定标签。

关键要点

  • 函数用于检测查询是否针对现有标签存档页面,返回布尔值。
  • 可选参数 $tag 可以是标签 ID、名称、slug 或其数组,用于精确匹配。
  • 函数内部调用 WP_Query::is_tag(),并包含错误处理,确保在查询运行后使用。
  • 常用于主题开发中,结合其他条件标签实现页面逻辑控制。

代码示例

// 当显示任何标签存档页面时。
is_tag();

// 当显示标签 ID 为 30 的存档页面时。
is_tag( '30' );

// 当显示 slug 为 'extreme' 的标签存档页面时。
is_tag( 'extreme' );

// 当显示名称为 'mild' 的标签存档页面时。
is_tag( 'mild' );

/*
 * 当显示的帖子标签是 term_ID 30、slug "extreme" 或名称 "mild" 之一时返回 true。
 * 注意:数组功能在版本 3.7 中添加。
 */
is_tag( array( 30, 'mild', 'extreme' ) );

注意事项

  • 条件查询标签在查询运行前无效,否则始终返回 false,函数包含 _doing_it_wrong() 警告。
  • 建议参考主题开发者手册中的条件标签文章以了解更多类似函数。

📄 原文内容

Determines whether the query is for an existing tag archive page.

Description

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

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

Parameters

$tagint|string|int[]|string[]optional
Tag ID, name, slug, or array of such to check against. Default empty.

Return

bool Whether the query is for an existing tag archive page.

Source

function is_tag( $tag = '' ) {
	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_tag( $tag );
}

Changelog

Version Description
2.3.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Examples

    // When any Tag archive page is being displayed.
    is_tag();
    
    // When the archive page for Tag 30 is being displayed.
    is_tag( '30' );
    
    // When the archive page for tag with the Slug of 'extreme' is being displayed.
    is_tag( 'extreme' );
    
    // When the archive page for tag with the Name of 'mild' is being displayed.
    is_tag( 'mild' );
    
    /*
     * Returns true when the tag of posts being displayed is either term_ID 30,
     * or slug "extreme", or name "mild". Note: the array ability was added
     * at Version 3.7.
     */
    is_tag( array( 30, 'mild', 'extreme' ) );