Created
March 4, 2012 14:28
-
-
Save cecilemuller/1973248 to your computer and use it in GitHub Desktop.
taxonomy_select_nodes with multiple terms, in Drupal 7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
beautiful function!!! Thank you