
get_the_category() 返回当前文章所属分类的数组集合
用法:<?php get_the_category( $id ) ?>
参数:$id 文章id,默认是当前文章ID,类型为整数,可选
返回的值:数组
示例:
eg1:如果需要使用返回的分类目录下的某个值,需要指定数组索引。可以这样理解,一篇文章可能属于多个分类目录,然后遍历返回结果可以获取每个分类的对象,再使用成员就即可获取想要的分类ID及分类名和其它内容。
<?php
$category = get_the_category(); //默认获取当前分类ID
echo $category[0]->cat_name; //使用$categories->cat_name不能获得正确值,应该$categories[0]->cat_name才能正确工作。
?>
eg2:在文章页循环当前文章所属分类,输出图片以分类ID命名,且alt属性设置为分类名称。
<?php
foreach((get_the_category()) as $category) {
echo ‘<img src=”http://example.com/images/’.$category->cat_ID.’.jpg” alt=”‘.$category->cat_name.'” />’;
}
?>
eg3:通过当前分类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(); ?>
eg4:在文章页通过指定的文章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;
?>
返回值各项含义:
cat_ID
分类id
cat_name
分类名
category_nicename
一个slug,也就是系统根据分类名生成的url友好的名字
category_description
分类描述
category_parent
父分类id
category_count
该分类包含多少篇日志或者该分类被使用了多少次
转载请注明:夜阑小雨 » wordpress获取当前文章分类数据