函数文档

the_tags()

💡 云策文档标注

概述

the_tags() 是 WordPress 模板标签函数,用于在循环中显示当前文章的标签列表。它支持自定义标签前后的文本和分隔符,并默认输出为“Tags:”前缀的逗号分隔列表。

关键要点

  • 函数用于在 The Loop 中显示文章标签,无需传递文章 ID。
  • 参数包括 $before(标签前文本,默认 'Tags:')、$sep(分隔符,默认 ', ')和 $after(标签后文本,默认空)。
  • 内部调用 get_the_tag_list() 获取格式化字符串,并使用 __() 进行本地化处理。
  • 返回值为标签对象数组,但通常直接输出 HTML 字符串。

代码示例

// 默认用法:输出“Tags: tag1, tag2”
the_tags();

// 自定义分隔符和前缀:输出“Social tagging: tag1 > tag2”
the_tags( 'Social tagging: ', ' > ' );

// 作为无序列表输出
the_tags( '<ul><li>', '</li><li>', '</li></ul>' );

注意事项

  • 函数在 The Loop 中使用时自动获取当前文章标签,否则需确保文章上下文正确。
  • 参数 $before 默认值为 null,但实际输出时转换为本地化的“Tags:”。
  • 使用 is_wp_error() 检查错误,确保输出稳定性。

📄 原文内容

Displays the tags for a post.

Parameters

$beforestringoptional
String to use before the tags. Defaults to 'Tags:'.

Default:null

$sepstringoptional
String to use between the tags. Default ‘, ‘.
$afterstringoptional
String to use after the tags. Default empty.

More Information

This function returns an array of objects, one object for each tag assigned to the post. If this function is used in The Loop, then no ID need be passed.

Source

function the_tags( $before = null, $sep = ', ', $after = '' ) {
	if ( null === $before ) {
		$before = __( 'Tags: ' );
	}

	$the_tags = get_the_tag_list( $before, $sep, $after );

	if ( ! is_wp_error( $the_tags ) ) {
		echo $the_tags;
	}
}

Changelog

Version Description
2.3.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Default Usage
    The default usage lists tags with each tag (if more than one) separated by a comma (,) and preceded with the default text Tags: .

    <p></p>

    Separated by Commas
    Displays a list of the tags with a line break after it.

    ' ); ?> 

    Separated by Arrow
    Displays links to tags with an arrow (>) separating the tags and preceded with the text Social tagging:

     ' ); ?>

    Separated by a Bullet
    Displays links to tags with a bullet (•) separating the tags and preceded with the text Tagged with: and followed by a line break.

    ' ); ?>

    A List Example
    Displays a list of the tags as an unordered list:

    <li>', '</li><li>', '</li></ul>' ); ?>