免费《新手做网站视频教程》,在线观看,如果你想从零开始自己做网站,点击开始吧!

WordPress文章页(single页)获取文章所属分类名和URL

  1. 首页
  2. »
  3. 图文教程
  4. »
  5. WordPress建站教程
  6. »
  7. WordPress文章页(single页)获取文章所属分类名和URL

文章目录

这种代码一般我们会用在面包屑上:

非常简单,一句话代码即可获取当前文章所属分类的url和名称:

<?php
the_category(‘,’);
?>

输出的html代码为:

<a href=”https://www.xuezuowangzhan.cn/./jz/zuowangzhan-day-1″ rel=”category tag”>新手做网站教程(第一天)</a> </li>

 

封装的方法:

需要用到下面三个函数

获取当前文章的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>’;
}
echo _get_category_post(get_the_ID());

推荐阅读

联系我