取得無線級樹狀分類
我相信物件導向是Wordpress未來發展方向,所以本文使用 Class WP_Term_Query 取得所有分類,而不是使用 get_terms 方法,代碼如下:
$args = array( 'taxonomy' => 'category', 'orderby' => 'name', 'order' => 'ASC', 'hierarchical' => true, 'hide_empty' => false, ); $the_query = new WP_Term_Query($args); $categories = $the_query->get_terms();
會返回 WP_Term 物件陣列,結構如下:
Array{ [0] => WP_Term Object ( [term_id] => 37 [name] => 天南地北 [slug] => chat [term_group] => 0 [term_taxonomy_id] => 37 [taxonomy] => category [description] => [parent] => 35 [count] => 0 [filter] => raw ) [1] => WP_Term Object ( [term_id] => 35 [name] => 服務專區 [slug] => service [term_group] => 0 [term_taxonomy_id] => 35 [taxonomy] => category [description] => [parent] => 0 [count] => 0 [filter] => raw ) }
為了讓之後選單可以判斷目前層數,以方便縮排…等動作,所以這邊透過 get_ancestors() 取得目前分類的祖先層級,並用count()計算深度,最後再建立這兩個物件成員,以利之後判斷
foreach($categories as $category){ $ancestors = get_ancestors( $category->term_id, 'category' ); $category->ancestors = $ancestors; // array( 0 => 15, 1 => 45 ) - 3rd level term $category->depth = count( $ancestors ) ; }
目前 Class WP_Term_Query 似乎沒有沒有相關方法處理無限級菜單資料,所以我們透過 get_cat_tree 這個方法,用遞迴的方式返回菜單的巢狀的陣列資料,陣列的值仍然是WP_Term 物件。
function get_cat_tree($parent,$categories) { $result = array(); foreach($categories as $category){ if ($parent == $category->parent) { $category->children = get_cat_tree($category->term_id,$categories); $result[] = $category; } } return $result; } $cats_tree = get_cat_tree(0,$categories);