在企業網站中,點擊根分類時,顯示當前根分類下的子分類,這是個很常見的需求,大多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建站有所幫助。





