在开发wordpress主题时,我们会在很多地方用到,获取当前文章的分类和链接,因此我们需要熟练地掌握此方法,下面说一下如何获取当前文章的分类名称和链接。

需要用到下面三个函数

获取当前文章的ID:get_the_ID()

获取当前文章的分类:get_the_category($postid) //传入文章ID

获取当前文章的链接:get_term_link($slug, $taxonomy) //传入get_the_category中返回的 slug和taxonomy字段即可。

可以根据具体使用时,封装对应的方法,下面是我封装的方法

function _get_category_post($postid)

{

$postid = !empty($postid) && $postid > 0 ? $postid : get_the_ID();

$category = get_the_category($postid);

$name = $category[0]->name;

$link = get_term_link($category[0]->slug, $category[0]->taxonomy);

return'<a href="'.$link.'">'.$name.'</a><i></i>';

}