Skip to content

Instantly share code, notes, and snippets.

@hitsujixgit
Created June 19, 2014 11:09
Show Gist options
  • Save hitsujixgit/081e02536f2391a7768d to your computer and use it in GitHub Desktop.
Save hitsujixgit/081e02536f2391a7768d to your computer and use it in GitHub Desktop.
カテゴリIDを階層順に並べた配列をつくる
<?php
function get_categories_tree() {
$post_categories = get_the_category();
$cat_trees = array();
$cat_counts = array();
$cat_depth_max = 10;
foreach ( $post_categories as $post_category ) {
$depth = 0;
$cat_IDs = array($post_category->cat_ID);
$cat_obj = $post_category;
while ( $depth < $cat_depth_max ) {
if ( $cat_obj->category_parent == 0 ) {
break;
}
$cat_obj = get_category($cat_obj->category_parent);
array_unshift($cat_IDs, $cat_obj->cat_ID);
$depth++;
}
array_push($cat_trees, $cat_IDs);
array_push($cat_counts, count($cat_IDs));
}
$depth_max = max($cat_counts);
$cat_key = array_search($depth_max, $cat_counts);
$cat_tree = $cat_trees[$cat_key];
return $cat_tree;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment