一般稍微复杂一点的 WordPress 网站都会有自定义文章及分类,比如 OZABC 导航的博客问答问题就是一种自定义分类文章。那么在当前自定义文章中如何获取所属分类的 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、名称、描述和别名就简单多了。在当前自定义文章文件中添加以下代码即可(假如当前文章属于自定义分类 notice,这个是自定义分类类型,而不是自定义文章类型哦):
$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 对象内容和上述代码进行修改即可。
如若转载,请注明出处:https://www.ozabc.com/jianzhan/355366.html