Hôm nay chúng ta thêm 1 hàm nữa. Hàm này giúp chúng ta lấy toàn bộ category theo các cấp độ level và theo parent nữa.
-
Hàm hiển thị category theo level
Các bạn chèn đoạn code sau vào file functions.php trong theme của bạn nhé.
1234567891011121314151617181920212223242526272829function get_level($category, $level = 0){if ($category->category_parent == 0) {return $level;} else {$level++;$category = get_category($category->category_parent);return get_level($category, $level);}}function display_cat_level( $level = 0 , $link = false, $parent = NULL){$catArgs = array( 'hide_empty' => 0);if( $parent != NULL ){$catArgs['child_of'] = $parent;}$cats = get_categories( $catArgs );if( $cats ){foreach($cats as $cat){$current_cat_level = get_level($cat);if( $current_cat_level == $level ){if($link==true) {echo ''.$cat->name."
";} else {echo $cat->name."
";}}}}}Sau đó muốn hiển thị ở đâu thì dùng hàm display_cat_level(,true/false,);
Ví dụ: như hình trên ta muốn hiển thị level 0 thì sẽ là1display_cat_level(0,true);//True nếu muốn có link, false không có linkMuốn hiển thị level 1 thì thế này:
1display_cat_level(1,true);//True nếu muốn có link, false không có linkMuốn hiển thị level 2 của cat có ID 3 thì thế này
1display_cat_level(2,true,3);//True nếu muốn có link, false không có link
Chúc các bạn thành công!
Nguồn: levantoan[.]com










