Tuesday 21 April 2015

Drupal 7 Taxonomy Ordering

What I need to do was Order my taxonomy from Parent to Child .

There are a couple of solutions to this; but I had issue with both .  Lets have a look at those first before I give my programmatical solution.

Hierarchal Term Formatter : https://www.drupal.org/project/hierarchical_term_formatter

Unfortunately installing this on my existing Drupal site causes all the fields in any views that contain taxonomy to disappear :/ Shame as this would have been perfect.

2. to order them BY ID, or NAME, or WEIGHT.
You need to create in Advance (Views) a Relationship pointing to that Taxonomy Vocabulary
Then you can add a Sort Filter



However this was the code that sorted the issue for me.

/**
 * @file Orders Taxonomy

 *

 * @param $tid - expecting a tid  

 * @param $no_results - the number of results that you'd like to return

 * @param $order - which tid first - child or most senior parent ?

 *

 * @return returns a string .

 */



function rcn_taxonomy_order($tid, $no_results = 1, $order = 'first') {



  $wrapper = entity_metadata_wrapper('taxonomy_term', $tid);

  $all_parents = $wrapper->parents_all->value();



  ($order == 'last') ? $all_parents = array_reverse($all_parents) : $all_parents;



  $stitch_term_array = '';

  foreach ($all_parents as $key => $term) {

    ($key < $no_results) ? $stitch_term_array .= $term->name . ", " : '';

  }



  return rtrim($stitch_term_array, ', ');



}

No comments: