
一般稍微复杂一点的WordPress网站都会有自定义文章及分类,比如小编的WordPress问答就是一种自定义分类文章,俺小编在当前自定义文章中如何获取所属分类的 ID,或名称,或别名,或描述呢?其实,咋们也可以通过 get_the_terms()函数来获得这些值。
get_the_terms()函数的介绍
get_the_terms( int|WP_Post $post, string $taxonomy )
其中:
$post:(int|WP_Post) (必需) 帖子 ID 或对象
$taxonomy:(string) (必填) 分类名称
返回值:成功时返回 WP_Term 对象的数组
更多介绍请移步官方介绍
WP_Term 对象
[term_id] =>
[name] =>
[slug] =>
[term_group] =>
[term_taxonomy_id] =>
[taxonomy] =>
[description] =>
[parent] =>
[count] =>
[filter ] =>
[term_order]=>
get_the_terms()函数的使用
在理解了get_the_terms()函数和WP_Term对象之后,获取自定义类别的ID,名称,描述和别名要容易得多。将以下代码添加到当前自定义文章文件中(如果当前文章是自定义分类通知,这是自定义分类类型,而不是自定义文章类型):
$post_categories = get_the_terms( $post->ID, 'notice' );//获取自定义分类信息
if ( ! empty( $post_categories ) && ! is_wp_error( $post_categories ) ) {
echo $post_categories[0]->term_id;//输出自定义分类的 ID
echo $post_categories[0]->name;//输出自定义分类的名称
echo $post_categories[0]->description;//输出自定义分类的描述
echo $post_categories[0]->slug;//输出自定义分类的别名
}
如果要输出有关自定义分类的其他信息,请参阅WP_Term对象内容和上面的代码进行修改。
还没有评论,来说两句吧...