You are here

function _taxonomy_breadcrumb_node_get_lightest_term in Taxonomy Breadcrumb 7

Same name and namespace in other branches
  1. 6 taxonomy_breadcrumb.inc \_taxonomy_breadcrumb_node_get_lightest_term()

Returns the lightest term for a given node.

Parameters

$nid: A node id.

Return value

The lightest term id associated with the node.

1 call to _taxonomy_breadcrumb_node_get_lightest_term()
taxonomy_breadcrumb_node_view in ./taxonomy_breadcrumb.module
Implements hook_node_view().

File

./taxonomy_breadcrumb.inc, line 17
helper functions for taxonomy_breadcrumb

Code

function _taxonomy_breadcrumb_node_get_lightest_term($nid) {

  // Get the lightest vocabulary id.
  $query = db_select('node', 'n');
  $query
    ->distinct();
  $query
    ->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  $query
    ->join('taxonomy_term_data', 'ttd', 'ti.tid = ttd.tid');
  $query
    ->join('taxonomy_vocabulary', 'tv', 'ttd.vid = tv.vid');
  $query
    ->fields('tv', array(
    'vid',
  ));
  $query
    ->condition('n.nid', $nid, '=');
  $query
    ->orderBy('tv.weight');
  $query
    ->orderBy('tv.name');
  $query
    ->range(0, 1);
  $vid = $query
    ->execute()
    ->fetchField();

  // If a vocabulary was successfully retrieved.
  if ($vid) {

    // Retrieve the vocabularies terms associated with the node.
    $query = db_select('node', 'n');
    $query
      ->distinct();
    $query
      ->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
    $query
      ->join('taxonomy_term_data', 'ttd', 'ti.tid = ttd.tid');
    $query
      ->join('taxonomy_vocabulary', 'tv', 'ttd.vid = tv.vid');
    $query
      ->fields('ti', array(
      'tid',
    ));
    $query
      ->condition('n.nid', $nid, '=');
    $query
      ->condition('tv.vid', $vid, '=');
    $tids = $query
      ->execute()
      ->fetchCol();

    // If only a single term is associated with this node.
    if (count($tids) == 1) {
      return $tids[0];
    }
    else {

      // Get the vocabulary tree.
      $vtree = taxonomy_get_tree($vid);

      // Return the first associated term found.
      foreach ($vtree as $term) {
        if (in_array($term->tid, $tids)) {
          return $term->tid;
        }
      }
    }
  }
}