get_the_terms sorted
-
So i had recently problem with sorting custom categories selected to single custom post and make a tree from it (nice navigation stuff)
Now i want to share my work:
$single_post = get_post(); $categories = get_the_terms($single_post->ID,$single_post->post_type.'_category');
This gets you categories but the problem is they aren’t sorted by term_id and parent so what i did is modyfying some function found on the web and making it sort.
function parentChildSort_r($idField, $parentField, $els, $parentID = 0, &$result = array(), &$depth = 0){ foreach ($els as $key => $value): $value=(array) $value; if ($value[$parentField] == $parentID){ $value['depth'] = $depth; array_push($result, $value); unset($els[$key]); $oldParent = $parentID; $parentID = $value[$idField]; $depth++; parentChildSort_r($idField,$parentField, $els, $parentID, $result, $depth); $parentID = $oldParent; $depth--; } endforeach; foreach($result as $k => $v) { $result_sorted[$k] = new stdClass(); foreach ($v as $key => $value) $result_sorted[$k]->$key = $value; } return $result_sorted; }
- The topic ‘get_the_terms sorted’ is closed to new replies.