欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

wordpress調(diào)用當前分類下子分類的方法

  發(fā)布時間:2015-01-06 12:08:44   作者:佚名   我要評論
這篇文章主要為大家介紹了wordpress調(diào)用當前分類下子分類的方法,通過添加自定義函數(shù)實現(xiàn)針對子分類的調(diào)用,是非常實用的技巧,需要的朋友可以參考下

本文實例講述了wordpress調(diào)用當前分類下子分類的方法。分享給大家供大家參考。具體分析如下:

自己沒用過wordpress博客但是個人認為wordpress有函數(shù)可直接來子調(diào)用當前分類下的子分類的,但是我找了很久沒找到,后來找到一具朋友自己的做法,下面我來整理一下.

在企業(yè)網(wǎng)站中,點擊根分類時,顯示當前根分類下的子分類,這是個很常見的需求,大多cms也能實現(xiàn)這個功能,如果使用wordpress架構(gòu),可以嗎?

答案是肯定的,wordpress也可以實現(xiàn)這樣的功能.

其實主要用到wp_list_categorys()函數(shù),該函數(shù)的child_of參數(shù)是一個數(shù)字,顯示指定ID(也就是所填的這個數(shù)字)下的子分類,這樣只要找到當前分類根分類的ID就可以顯示了。

the_category_ID()用于顯示當前頁面的分類ID,默認是輸出的,作為參數(shù)傳遞時,最好傳入一個false參數(shù),即the_category_ID(false)獲取當前分類ID。

接著就是要獲取當前分類的父ID,這個也是本文的重中之重,扒了很多資料,也沒找到直接可以實現(xiàn)的,不過通過一個函數(shù),倒可以間接獲取,代碼如下:

復制代碼
代碼如下:
function get_category_root_id($cat)
{
$this_category = get_category($cat); // 取得當前分類
while($this_category->category_parent) // 若當前分類有上級分類時,循環(huán)
{
$this_category = get_category($this_category->category_parent); // 將當前分類設為上級分類(往上爬)
}
return $this_category->term_id; // 返回根分類的id號
}

實例2:

1.現(xiàn)在function.php里面添加下面的代碼:

復制代碼
代碼如下:
function get_category_root_id($cat)
{
$this_category = get_category($cat); // 取得當前分類
while($this_category->category_parent) // 若當前分類有上級分類時,循環(huán)
{
$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>';
}
}
?>

現(xiàn)在就萬事具備了,我們就實現(xiàn)一下吧,代碼如下:

復制代碼
代碼如下:
wp_list_categories("child_of=".get_category_root_id(the_category_ID(false)). "&depth=0&hide_empty=0&title_li=");

獲得WordPress指定分類(包括子分類)下的所有文章數(shù),代碼如下:

復制代碼
代碼如下:
$parent_array = get_categories('hide_empty=0&parent=79');
//使用get_categories()函數(shù),里面參數(shù)的意思是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; //第三極子分類下文章數(shù)進行統(tǒng)計
}
$sub_count +=$vv->category_count; //第二級子分類下文章數(shù)進行統(tǒng)計
}
$count +=$v->category_count; //第一級子分類下文章數(shù)進行統(tǒng)計
}
$total = $count+$sub_count+$three_count;
//將第一級和第二級和第三級統(tǒng)計的文章數(shù)目進行相加后放到一個變量中。

這樣我們通過php的foreach循環(huán)用很少的代碼就將一個分類下的文章數(shù)目統(tǒng)計出來了。

希望本文所述對大家的WordPress建站有所幫助。

相關(guān)文章

最新評論