当前浏览:首页 / WordPress函数 / get_category()

get_category( int|object $category, string $output = OBJECT, string $filter = 'raw' )

检索给定ID或对象的类别数据

cat

category 分类more...


描述

如果将对象传递给$category参数,则假定该对象是数据库检索到的类别行对象,它将缓存类别数据。

如果将类别ID的整数传递给$category,则将从数据库中检索该类别(如果尚未缓存),并返回结果。

如果查看get_term(),可以发现这两个函数都将通过几个过滤器,并最终根据$filter参数值对数据进行净化清理。


参数

$category

(int|object) (必填) 类别ID或类别行对象

$output

(string) (可选) 所需的返回类型。OBJECT、ARRAY_A或ARRAY_N中的一个,分别对应于WP_Term对象、关联数组或数字数组。

默认值: OBJECT

$filter

(string) (可选) 如何清理类别字段

默认值: 'raw'


返回

(object|array|WP_Error|null) 类别数据的类型由$output参数定义。如果$category为空则返回WP_Error,如果不存在,则为null。



源码

查看源码 官方文档


更新日志

版本描述
1.5.1开始引入

使用示例

  • 示例1

    传递类别ID(整数)的示例:

    <?php $category = get_category( 106 ); ?>

    print_r( $category ); 的输出类似于:

    stdClass Object
    (
    [term_id] => 106
    [name] => Category Name
    [slug] => category-name
    [term_group] => 0
    [term_taxonomy_id] => 108
    [taxonomy] => category
    [description] => This is the category description.
    [parent] => 62
    [count] => 17
    [filter] => raw
    [cat_ID] => 106
    [category_count] => 17
    [category_description] => This is the category description.
    [cat_name] => Category Name
    [category_nicename] => category-name
    [category_parent] => 62
    )

  • 示例2

    检查具有cat ID的类别是否有任意数量的文章。

    if ( get_category( $id )->category_count > 1 ) {
       //do something
    }
    
  • 示例3

    在类别模板上获取当前类别数据:

    $current_category = get_category( get_query_var( 'cat' ), false );