Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Created March 4, 2012 14:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cecilemuller/1973248 to your computer and use it in GitHub Desktop.
Save cecilemuller/1973248 to your computer and use it in GitHub Desktop.
taxonomy_select_nodes with multiple terms, in Drupal 7
<?php
/**
* In Drupal 6, `taxonomy_select_nodes` was able to filter by multiple terms,
* but Drupal 7 accepts only one TermID.
*/
function taxonomy_select_nodes_multiple($tids = array(), $operator = 'or'){
$nids = array();
if (variable_get('taxonomy_maintain_index_table', TRUE)){
switch($operator){
case 'or':
$query = 'SELECT DISTINCT(nid) FROM {taxonomy_index} WHERE tid IN(' . implode(',', $tids) . ')';
break;
case 'and':
$i = 0;
foreach ($tids as $tid){
if ($i == 0){
$tables = 't0.nid FROM {taxonomy_index} t0 ';
$where = "t0.tid = $tid ";
} else {
$tables .= "LEFT JOIN {taxonomy_index} t$i ON (t$i.nid = t".($i - 1).'.nid) ';
$where .= "AND t$i.tid = $tid ";
}
$i ++;
}
$query = "SELECT $tables WHERE $where ORDER BY t0.nid ASC";
break;
}
}
if (!empty($query)) $nids = db_query($query)->fetchCol();
return $nids;
}
?>
@giacy86
Copy link

giacy86 commented Jun 5, 2014

beautiful function!!! Thank you

@asadpakistani
Copy link

Thanks man, You ROCK!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment