You are here

function views_node_taxonomy_filter_handler_filter_tid::query in Views Node Taxonomy Filter 7

Same name and namespace in other branches
  1. 6 views_node_taxonomy_filter_handler_filter_tid.inc \views_node_taxonomy_filter_handler_filter_tid::query()

Modify the query appropriately.

Overrides views_handler_filter::query

File

./views_node_taxonomy_filter_handler_filter_tid.inc, line 104

Class

views_node_taxonomy_filter_handler_filter_tid
@file

Code

function query() {
  if (empty($this->value[0])) {
    return;
  }
  $allowed_vocabs = $this->value[0];
  if (arg(0) != 'node') {
    return;
  }
  $nid = arg(1);
  if (!is_numeric($nid)) {
    return;
  }
  $node = node_load($nid);
  $langcode = empty($node->language) ? LANGUAGE_NONE : $node->language;
  $tids = array();
  $list_vocabs = array();
  $fields = field_info_fields();

  //This is going to give us all taxonomy reference fields
  foreach ($fields as $name => $field) {
    if ($field['type'] == 'taxonomy_term_reference') {
      $vocabs[$field['settings']['allowed_values'][0]['vocabulary']][] = $field['field_name'];
    }
  }

  //find which field is the field we're looking for
  foreach ($allowed_vocabs as $allowed) {
    if (in_array($allowed, array_keys($vocabs))) {
      $term_fields = $vocabs[$allowed];
    }
  }

  //we have all the fields using the given vocab, grab the terms
  foreach ($term_fields as $term_field) {
    if (isset($node->{$term_field}) && !empty($node->{$term_field})) {
      $node_term_set = $node->{$term_field};
      if ($langcode) {
        foreach ($node_term_set[$langcode] as $term) {

          //if selected, get all children for the term
          if ($this->value[1] == 1) {
            $tids[] = $term['tid'];
            $children = taxonomy_get_children($term['tid']);
            foreach ($children as $child) {
              $tids[] = $child->tid;
            }
          }
          else {
            $tids[] = $term['tid'];
          }
        }
      }
      else {
        foreach ($node_term_set as $term) {

          //if selected, get all children for the term
          if ($this->value[1] == 1) {
            $tids[] = $term['tid'];
            $children = taxonomy_get_children($term['tid']);
            foreach ($children as $child) {
              $tids[] = $child->tid;
            }
          }
          else {
            $tids[] = $term['tid'];
          }
        }
      }
    }
  }
  if (sizeof($tids) < 1) {

    //if we want to require this relationship, make tids 0 - there will never be terms with tid = 0 (autoincrement starts at 1)
    if (isset($this->value[2]) && $this->value[2]) {
      $tids = 0;
    }
    else {
      return;
    }
  }
  else {
    $tids = implode(',', $tids);
  }
  $alias = $this->query
    ->ensure_table('taxonomy_index');
  $this->query
    ->add_where_expression($this->options['group'], "{$alias}.tid IN ({$tids})");
}