get_the_tag_list()
云策文档标注
概述
get_the_tag_list() 函数用于获取文章标签并格式化为字符串,每个标签名称会链接到对应的标签页面。该函数必须在 The Loop 内使用,并允许自定义标签前后的分隔符。
关键要点
- 函数返回一个 HTML 字符串,包含当前文章的标签列表,标签名带有链接。
- 参数包括 $before(标签前字符串)、$sep(标签间分隔符)、$after(标签后字符串)和 $post_id(文章 ID),默认值均为空或当前文章。
- 返回值类型为 string|false|WP_Error:成功时返回标签列表字符串,无标签时返回 false,失败时返回 WP_Error。
- 与 get_the_category_list() 不同,此函数必须在 The Loop 内调用。
- 通过 apply_filters('the_tags', ...) 钩子可过滤标签列表。
代码示例
// 基本示例:输出标签列表,标签前加“Tags: ”并用逗号分隔
echo get_the_tag_list( sprintf( '%s: ', __( 'Tags', 'textdomain' ) ), ', ', '' );
// 复杂示例:检查是否有标签并输出到无序列表
$tag_list = get_the_tag_list( '', '', '' );
if ( $tag_list && ! is_wp_error( $tag_list ) ) {
echo $tag_list;
}注意事项
- 函数必须在 The Loop 内使用,否则可能无法正确获取文章标签。
- 返回值可能为 false 或 WP_Error,建议在输出前进行错误检查。
- 可通过 CSS 对输出的 HTML 字符串添加样式和类。
原文内容
Retrieves the tags for a post formatted as a string.
Parameters
$beforestringoptional-
String to use before the tags. Default empty.
$sepstringoptional-
String to use between the tags. Default empty.
$afterstringoptional-
String to use after the tags. Default empty.
$post_idintoptional-
Post ID. Defaults to the current post ID.
Source
function get_the_tag_list( $before = '', $sep = '', $after = '', $post_id = 0 ) {
$tag_list = get_the_term_list( $post_id, 'post_tag', $before, $sep, $after );
/**
* Filters the tags list for a given post.
*
* @since 2.3.0
*
* @param string $tag_list List of tags.
* @param string $before String to use before the tags.
* @param string $sep String to use between the tags.
* @param string $after String to use after the tags.
* @param int $post_id Post ID.
*/
return apply_filters( 'the_tags', $tag_list, $before, $sep, $after, $post_id );
}
Hooks
- apply_filters( ‘the_tags’, string $tag_list, string $before, string $sep, string $after, int $post_id )
-
Filters the tags list for a given post.
Changelog
| Version | Description |
|---|---|
| 2.3.0 | Introduced. |
Skip to note 3 content
Codex
A Slightly More Complex Example
This checks if the post has any tags, and if there are, outputs them to an unordered list.
/** @var string|false|WP_Error $tag_list */ $tag_list = get_the_tag_list( '<ul><li>', '</li><li>', '</li></ul>' ); if ( $tag_list && ! is_wp_error( $tag_list ) ) { echo $tag_list; }This will return something in the form:
[html]
…
[/html]
You can add classes and styles with CSS, as necessary.
Skip to note 4 content
Codex
A Basic Example
This outputs the list of tags inside a paragraph, with tags separated by commas.
echo get_the_tag_list( sprintf( '<p>%s: ', __( 'Tags', 'textdomain' ) ), ', ', '</p>' );This would return something like:
[html]
Tags: Tag 1, Tag 2, …
[/html]