Skip to content

Instantly share code, notes, and snippets.

@hissy
Created November 19, 2013 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hissy/7540878 to your computer and use it in GitHub Desktop.
Save hissy/7540878 to your computer and use it in GitHub Desktop.
[WordPress] カテゴリーを階層の深い順に並び替える
<?php
// Get categories of current post
$_cats = get_the_terms( get_post(), 'category');
$_sort = array();
$cats = array();
// Get the depth of each categories
foreach( $_cats as $_cat ) {
$depth = count( get_ancestors( $_cat->term_id, 'category' ) );
$_sort[$_cat->term_id] = $depth;
}
// Sort by depth
arsort($_sort);
// Build sorted array of categories
foreach( $_sort as $id => $depth ) {
$cats[$id] = $_cats[$id];
}
unset($_cats);
unset($_sort);
// done!
var_dump($cats);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment