在wordpress 中。获取文章分类的办法有很多。
最常见的是下面这个代码段
function custom_taxonomies_terms_links(){
//根据当前文章ID获取文章信息
$post = get_post( $post->ID );
//获取当前文章的文章类型
$post_type = $post->post_type;
//获取文章所在的自定义分类法
$taxonomies = get_object_taxonomies( $post_type, 'objects' );
$out = array();
foreach ( $taxonomies as $taxonomy_slug => $taxonomy ){
$term_list = wp_get_post_terms($post->ID, $taxonomy_slug, array("fields" => "all"));
echo $term_list[0]->name; //显示文章所处的分类中的第一个
}
return implode('', $out );
}
但后面经过自己重新编写。更加简短,更加符合自己的要求
代码如下
/**
*获取分类
**/
function deel_category(){
$tag_arr = get_the_category();
foreach($tag_arr as $value){
if(!empty($value)){
echo '<a data-bear="main" href='.get_term_link($value->slug,$value->taxonomy).'>'.$value->name.'<a>';
}
}
}
把这段代码放到functions.php 中去。然后在需要显示分类的位置插上 <?php deel_category();?>。
get_the_category() 返回当前文章所属分类的数组集合
用法:
参数:$id 文章id,默认是当前文章ID,类型为整数,可选
返回的值:数组
数组的格式如下图所示
其中我们最需要用到的当然就是name 啦
但当你需要给 name分类 添加 a 标签时,这时需要一个wp函数来获取分类的地址
函数get_term_link 是用来获取分类地址的
使用方式
<?php get_term_link( $term, $taxonomy ); ?>
我们将get_the_category返回的数组中的slug 和 taxonomy 字段传入到这个函数,即可获取到分类对应的地址了
转载于:https://blog.51cto.com/kinpui/1709089