the_terms()
云策文档标注
概述
the_terms() 函数用于在 WordPress 中显示指定文章的术语列表,支持自定义前后缀和分隔符。它基于 get_the_term_list() 实现,并包含一个过滤器钩子用于修改输出。
关键要点
- 函数签名:the_terms( $post_id, $taxonomy, $before = '', $sep = ', ', $after = '' )
- 参数:$post_id(必需,文章 ID)、$taxonomy(必需,分类法名称)、$before(可选,术语前字符串)、$sep(可选,术语间分隔符)、$after(可选,术语后字符串)
- 返回值:成功时返回 void,失败时返回 false
- 内部使用 get_the_term_list() 获取术语列表,并通过 apply_filters('the_terms', ...) 应用过滤器
- 相关函数:get_the_term_list()、apply_filters()、is_wp_error()
代码示例
the_terms( get_the_ID(), 'category', 'categories: ', ' / ' );注意事项
- 输出为带链接的术语列表,适用于分类、标签等自定义分类法
- 自 WordPress 2.5.0 版本引入
原文内容
Displays the terms for a post in a list.
Parameters
$post_idintrequired-
Post ID.
$taxonomystringrequired-
Taxonomy name.
$beforestringoptional-
String to use before the terms. Default empty.
$sepstringoptional-
String to use between the terms. Default ‘, ‘.
$afterstringoptional-
String to use after the terms. Default empty.
Source
function the_terms( $post_id, $taxonomy, $before = '', $sep = ', ', $after = '' ) {
$term_list = get_the_term_list( $post_id, $taxonomy, $before, $sep, $after );
if ( is_wp_error( $term_list ) ) {
return false;
}
/**
* Filters the list of terms to display.
*
* @since 2.9.0
*
* @param string $term_list List of terms to display.
* @param string $taxonomy The taxonomy name.
* @param string $before String to use before the terms.
* @param string $sep String to use between the terms.
* @param string $after String to use after the terms.
*/
echo apply_filters( 'the_terms', $term_list, $taxonomy, $before, $sep, $after );
}
Hooks
- apply_filters( ‘the_terms’, string $term_list, string $taxonomy, string $before, string $sep, string $after )
-
Filters the list of terms to display.
Changelog
| Version | Description |
|---|---|
| 2.5.0 | Introduced. |
Skip to note 3 content
Codex
Get Categories of Current Post
Get a list of current post’s categories:
ID, 'category', 'categories: ', ' / ' ); ?>The output of the above code could be: categories: TV / Speaker / Monitor
Skip to note 4 content
Wilgax
I just wanted to add that the above piece of code will output the categories as href links.
E.g. Output of the code:
ID, 'category', 'categories: ', ' / ' ); ?>will be in the form:
categories: <a href="http://example.com/category/tv" rel="nofollow">TV</a> / <a href="http://example.com/category/speaker" rel="nofollow">Speaker</a> / <a href="http://example.com/category/monitor" rel="nofollow">Monitor</a>