阅读原文获取更佳体验
php
在wordpress 中。获取文章分类的办法有不少。数组
最多见的是下面这个代码段ide
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 ); }
但后面通过本身从新编写。更加简短,更加符合本身的要求wordpress
代码以下函数
/** *获取分类 **/ 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();?>。post
get_the_category() 返回当前文章所属分类的数组集合spa
用法:blog
参数:$id 文章id,默认是当前文章ID,类型为整数,可选get
返回的值:数组博客
数组的格式以下图所示
其中咱们最须要用到的固然就是name 啦
但当你须要给 name分类 添加 a 标签时,这时须要一个wp函数来获取分类的地址
函数get_term_link 是用来获取分类地址的
使用方式
<?php get_term_link( $term, $taxonomy ); ?>
咱们将get_the_category返回的数组中的slug 和 taxonomy 字段传入到这个函数,便可获取到分类对应的地址了