本文實(shí)例講述了wordpress調(diào)用當(dāng)前分類下子分類的方法。分享給大家供大家參考。具體分析如下:
自己沒用過wordpress博客但是個(gè)人認(rèn)為wordpress有函數(shù)可直接來子調(diào)用當(dāng)前分類下的子分類的,但是我找了很久沒找到,后來找到一具朋友自己的做法,下面我來整理一下.
在企業(yè)網(wǎng)站中,點(diǎn)擊根分類時(shí),顯示當(dāng)前根分類下的子分類,這是個(gè)很常見的需求,大多cms也能實(shí)現(xiàn)這個(gè)功能,如果使用wordpress架構(gòu),可以嗎?
答案是肯定的,wordpress也可以實(shí)現(xiàn)這樣的功能.
其實(shí)主要用到wp_list_categorys()函數(shù),該函數(shù)的child_of參數(shù)是一個(gè)數(shù)字,顯示指定ID(也就是所填的這個(gè)數(shù)字)下的子分類,這樣只要找到當(dāng)前分類根分類的ID就可以顯示了。
the_category_ID()用于顯示當(dāng)前頁(yè)面的分類ID,默認(rèn)是輸出的,作為參數(shù)傳遞時(shí),最好傳入一個(gè)false參數(shù),即the_category_ID(false)獲取當(dāng)前分類ID。
接著就是要獲取當(dāng)前分類的父ID,這個(gè)也是本文的重中之重,扒了很多資料,也沒找到直接可以實(shí)現(xiàn)的,不過通過一個(gè)函數(shù),倒可以間接獲取,代碼如下:
{
$this_category = get_category($cat); // 取得當(dāng)前分類
while($this_category->category_parent) // 若當(dāng)前分類有上級(jí)分類時(shí),循環(huán)
{
$this_category = get_category($this_category->category_parent); // 將當(dāng)前分類設(shè)為上級(jí)分類(往上爬)
}
return $this_category->term_id; // 返回根分類的id號(hào)
}
實(shí)例2:
1.現(xiàn)在function.php里面添加下面的代碼:
{
$this_category = get_category($cat); // 取得當(dāng)前分類
while($this_category->category_parent) // 若當(dāng)前分類有上級(jí)分類時(shí),循環(huán)
{
$this_category = get_category($this_category->category_parent); // 將當(dāng)前分類設(shè)為上級(jí)分類(往上爬)
}
return $this_category->term_id; // 返回根分類的id號(hào)
}
2.然后在頁(yè)面要顯示二級(jí)分類的地方粘貼下面這段代碼即可
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)在就萬事具備了,我們就實(shí)現(xiàn)一下吧,代碼如下:
獲得WordPress指定分類(包括子分類)下的所有文章數(shù),代碼如下:
//使用get_categories()函數(shù),里面參數(shù)的意思是hide_empty把子分類下沒有文章的也顯示出來
//parent 父級(jí)分類的ID號(hào)
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ù)進(jìn)行統(tǒng)計(jì)
}
$sub_count +=$vv->category_count; //第二級(jí)子分類下文章數(shù)進(jìn)行統(tǒng)計(jì)
}
$count +=$v->category_count; //第一級(jí)子分類下文章數(shù)進(jìn)行統(tǒng)計(jì)
}
$total = $count+$sub_count+$three_count;
//將第一級(jí)和第二級(jí)和第三級(jí)統(tǒng)計(jì)的文章數(shù)目進(jìn)行相加后放到一個(gè)變量中。
這樣我們通過php的foreach循環(huán)用很少的代碼就將一個(gè)分類下的文章數(shù)目統(tǒng)計(jì)出來了。
希望本文所述對(duì)大家的WordPress建站有所幫助。