> WordPress中文手册 > wordpress获取分类数据函数:get_the_category()

【函数介绍】

get_the_category() 返回当前文章所属分类的数组集合

【函数用法】

<?PHP get_the_category( $id ) ?>

【参数】

id
(整型) (可选) 文章 id.
默认: $post->ID (当前文章id)

【返回值】

返回值为一个分类对象数组
返回值各项含义:
cat_ID
分类id
cat_name
分类名
category_nicename
一个slug,也就是系统根据分类名生成的url友好的名字
category_description
分类描述
category_parent
父分类id
category_count
该分类包含多少篇日志或者该分类被使用了多少次

【示例】

示例1:如果需要使用返回的分类目录下的某个值,需要指定数组索引。可以这样理解,一篇文章可能属于多个分类目录,然后遍历返回结果可以获取每个分类的对象,再使用成员就即可获取想要的分类ID及分类名和其它内容。

<?php
    $category = get_the_category();   //默认获取当前分类ID
    echo $category[0]->cat_name;    //使用$categories->cat_name不能获得正确值,应该$categories[0]->cat_name才能正确工作。
?>

示例2:在文章页循环当前文章所属分类,输出图片以分类ID命名,且alt属性设置为分类名称。

<?php
     foreach((get_the_category()) as $category) {
          echo '<img src="http://example.com/images/'.$category->cat_ID.'.jpg" alt="'.$category->cat_name.'" />';
}
?>

示例3:通过当前分类id显示当前分类的所有的文章标题。

<?php
    $cat=get_the_category();
    $cat_id=$cat[0]->cat_ID;
    query_posts('order=asc&cat='.$cat_id);
    while (have_posts()):the_post();
?>
<a href="<?php the_permalink();?>"><?php the_title();?></a>
<?php  endwhile;wp_reset_query(); ?>

示例4:在文章页通过指定的文章ID获取此文章所属分类的相关信息。如分类名称,分类别名,分类描述,分类所包含的文章数。

<?php
    global $post;
    $categories = get_the_category($post->ID);
    //var_dump($categories);
    echo $categories[0]->cat_name;
    echo $categories[0]->category_nicename ;
    echo $categories[0]->category_description ;
    echo $categories[0]->category_count;
?>

【源代码】

get_the_category() 位于 wp-includes/category-template.php