好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

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

自己没用过wordpress博客但是个人认为wordpress有函数可直接来子调用当前分类下的子分类的,但是我找了很久没找到,后来找到一具朋友自己的做法,下面我来整理一下.

在企业网站中,点击根分类时,显示当前根分类下的子分类,这是个很常见的需求,大多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.然后在页面要显示二级分类的地方粘贴下面这段代码即可

<?php  if (is_single()||is_category())  {  if (get_category_children(get_category_root_id(the_category_ID(false)))!=  ""  )  {  echo   '<ul>' ;  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   '</ul>' ;  }  }  ?> 

现在就万事具备了,我们就实现一下吧,代码如下:

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 循环用很少的代码就将一个分类下的文章数目统计出来了 

查看更多关于wordpress中调用当前分类下的子分类代码 - WordPre的详细内容...

  阅读:57次