一聚教程网:一个值得你收藏的教程网站

热门教程

wordpress中调用当前分类下的子分类代码

时间:2022-06-25 19:13:47 编辑:袖梨 来源:一聚教程网

在企业网站中,点击根分类时,显示当前根分类下的子分类,这是个很常见的需求。大多cms也能实现这个功能。如果使用wordpress架构,可以吗?
答案是肯定的,wordpress也可以实现这样的功能。
其实主要用到wp_list_categorys()函数,该函数的child_of参数是一个数字,显示指定ID(也就是所填的这个数字)下的子分类。这样只要找到当前分类根分类的ID就可以显示了。

the_category_ID()用于显示当前页面的分类ID,默认是输出的,作为参数传递时,最好传入一个false参数,即the_category_ID(false)获取当前分类ID。
接着就是要获取当前分类的父ID,这个也是本文的重中之重。
扒了很多资料,也没找到直接可以实现的,不过通过一个函数,倒可以间接获取:

 代码如下 复制代码

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

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.然后在页面要显示二级分类的地方粘贴下面这段代码即可

 代码如下 复制代码

if(is_single()||is_category())
{
if(get_category_children(get_category_root_id(the_category_ID(false)))!= "" )
{
echo '

    ';
    echo wp_list_categories("child_of=".get_category_root_id(the_category_ID(false)). "&depth=0&hide_empty=0&title_li=&orderby=id&order=ASC");
    echo '
';
}
}
?>


现在就万事具备了,我们就实现一下吧!

 代码如下 复制代码


wp_list_categories("child_of=".get_category_root_id(the_category_ID(false)). "&depth=0&hide_empty=0&title_li=");


获得WordPress指定分类(包括子分类)下的所有文章数

 

 代码如下 复制代码

$parent_array = get_categories('hide_empty=0&parent=79');

//使用get_categories()函数,里面参数的意思是hide_empty把子分类下没有文章的也显示出来
//parent 父级分类的ID号

foreach($parent_array as $k=>$v)  //第一步
{

$sub_parent_array = get_categories('parent='.$v->cat_ID);

  foreach($sub_parent_array as $kk=>$vv)   //第二步
  {

     $three_parent_array = get_categories('hide_empty=0&parent='.$vv->cat_ID);

     foreach($three_parent_array as $kkk=>$vvv)  //第三步
     {
        $three_count +=$vvv->category_count;  //第三极子分类下文章数进行统计
     }

     $sub_count +=$vv->category_count;  //第二级子分类下文章数进行统计

  }
 $count +=$v->category_count;  //第一级子分类下文章数进行统计
}

$total = $count+$sub_count+$three_count;

//将第一级和第二级和第三级统计的文章数目进行相加后放到一个变量中。

这样我们通过php的foreach循环用很少的代码就将一个分类下的文章数目统计出来了

热门栏目