List nodes tagged with a certain term
Last modified: April 13, 2007 - 14:10
This PHP snippet will allow you to create a custom block listing a specified number of nodes on the site tagged with a certain tag. Note that it doesn't check access controls, so if that is necessary for your implementation, don't forget to add that check in to the code.
<?php
// tag to use:
$tag = 'newsletter';
// maximum number of items to show:
$count = 6;
$result = db_query_range(db_rewrite_sql("SELECT n.nid, n.title
FROM {node} n
INNER JOIN {term_node} tn ON n.nid = tn.nid
INNER JOIN {term_data} td ON tn.tid = td.tid
WHERE td.name = '%s' AND
n.status = 1
ORDER BY n.created DESC"),$tag,0,$count);
while ($node = db_fetch_object($result)) {
$items[] = l($node->title, 'node/'. $node->nid);
}
$output = theme('item_list', $items);
print $output;
?>For multiple tags you could use something like:
<?php
// tag to use:
$tags = "'tag1','tag2','tag3'";
// maximum number of items to show:
$count = 6;
$result = db_query_range(db_rewrite_sql("SELECT n.nid, n.title
FROM {node} n
INNER JOIN {term_node} tn ON n.nid = tn.nid
INNER JOIN {term_data} td ON tn.tid = td.tid
WHERE td.name IN (%s) AND
n.status = 1
ORDER BY n.created DESC"),$tags,0,$count);
while ($node = db_fetch_object($result)) {
$items[] = l($node->title, 'node/'. $node->nid);
}
$output = theme('item_list', $items);
print $output;
?>