首页 论坛 wordpress调用当前分类的子分类
帖子详情

在企业网站制作时,需要在网站的边栏列出企业产品分类,如果公司网站产品项目很多的情况,就需要设置二级分类或者子分类。如下图:

wordpress调用某个分类下的二级分类名

如何在自己建网站时显示当前分类下的子分类或者在文章页显示所属分类的子分类这样的问题,尤其在做wordpress中文主题的时候必须要用到这个技巧的。

方法/步骤

1.首先在网站主题的函数模板function.php里添加以下代码:

//调用子分类、
function get_category_root_id($cat)
{
$this_category = get_category($cat); // 取得当前分类
while($this_category->category_parent) // 若当前分类有上级分类时,循环
{
$this_category = get_category($this_category->category_parent); // 将当前分类设为上级分类(往上爬)
}
return $this_category->term_id; // 返回根分类的id号
}

2.然后在页面要显示子分类的地方(一般是在侧边栏)粘贴下面这段代码即可

<?php wp_list_cats('child_of=' . get_category_root_id($cat) . '&depth=1&hide_empty=0&hierarchical=1&optioncount=1');?>

如果想更灵活的调用当前分类下的子分类,可以使用下面的代码:

<?php
$args=array(
'child_of'=> get_category_root_id($cat),
'hide_empty'=>'0',
);
$categories=get_categories($args);
foreach($categories as $category) {
echo '<h3><a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a></h3>';
}
?>

相关知识:wordpress调用指定分类下的子分类

版权:言论仅代表个人观点,不代表官方立场。转载请注明出处:https://www.52diyhome.com/forum/65126.html

发表评论
暂无评论
  • 0 +

    访问总数

  • 0 +

    会员总数

  • 0 +

    资源总数

  • 0 +

    今日发布

  • 0 +

    本周发布

  • 0 +

    运行天数

资源在于分享,创作来源想象