sortingdrupaldrupal-7drupal-taxonomy

Load terms sorted by weight


Could anyone point me in the right direction when it comes to load terms from a vocabular in an ascending order based on the terms weight?

This is what i have now:

$taxonomy = taxonomy_vocabulary_machine_name_load('tool_type');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $taxonomy->vid));

From what i can see my terms are now sorted in an alphabetical order, this is not what i need.

I also find it weird that alphabetical order seems to be the standard when you can drag and drop the terms in the CMS to change the weight of the term. It would make much more sense if the terms were sorted by weight as standard. Can anyone explain to me why it is implemented this way?


Solution

  • You could sort them using the weight property of taxonomy items :

    $taxonomy = taxonomy_vocabulary_machine_name_load('tool_type');
    $terms = entity_load('taxonomy_term', FALSE, array('vid' => $taxonomy->vid));
    uasort($terms, function($a, $b) {
        if ($a->weight == $b->weight) return strcmp($a->name, $b->name) ;
        return $a->weight > $b->weight;
    });
    

    This will sort by weight. If weight are the same, sorted by name.