腾讯云服务器优惠活动华纳云香港服务器

WordPress如何获取文章所属分类ID、名称或别名?

WordPress主题推荐

在 wordpress 主题制作过程中,我们可能会经常用到当前分类 ID,如:在文章页获取该文章分类下的相关文章,这时就可能用到当前分类 ID,即当前文章所在的分类 ID。那么,wordpress 怎样获取当前分类目录 ID 呢?下面就一起跟随高时银博客来看看吧。

方法 1、变量$cat,只能在分类页使用 。

方法 2、global $wp_query; $cat_ID = get_query_var(‘cat’); 获取当前分类 ID 号,只能在分类页使用。

方法 3、在 page 单页面使用:

$cat= single_cat_title('', false);
echo get_cat_ID($cat);

方法 4、在主题中添加自定义函数,然后再调用这个函数。

function get_current_category_id() {
$current_category = single_cat_title('', false);//获得当前分类目录名称
return get_cat_ID($current_category);//获得当前分类目录 ID
}

获得当前分类目录 ID:

<?php echo get_current_category_id(); ?>

方法 5、通用,分类页和文章页都可以用。

$category = get_the_category();//默认获取当前所属分类
echo $category[0]->cat_ID; //输出分类 id

函数返回值:

  • cat_ID – 分类 ID ,
  • cat_name – 分类名 ,
  • category_nicename – 别名 ,
  • category_description – 分类描述 ,
  • category_parent – 父分类 ID ,
  • category_count – 包涵文章数量

以上就是我所总结的“获取 wordpress 当前分类目录 ID 号”的几种方法,仅供参考。

以上内容整理自@高时银博客

本文地址:https://boke112.com/post/4269.html

赞 (0) 打赏
版权声明:本文为原创文章,版权归 boke112百科 所有,欢迎分享本文,转载请保留出处!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu