Display latest X nodes from a taxonomy terms set

Last modified: March 14, 2009 - 00:15

The code below let display on a block (or a php page) a block with the latest X (configurable in the code) nodes associated with some taxonomy terms.

Let's imagine you have taxonomy terms "fruit" and "vegetable" which have term id as 49 and 50.
Then the code to display latest 10 entries in those terms is

<?php
// comma separated lists of terms tid to display nodes
$terms = "49,50";

// the number of nodes to show
$count = 10;


$sql = "SELECT n.title, n.nid FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid WHERE tn.tid in ($terms) AND n.status=1 ORDER BY n.created DESC";
$result = db_query_range(db_rewrite_sql($sql), 0, $count);
if (
$result) {
  return
node_title_list($result);
}
return
t('No nodes available.');
?>

Avoid Duplicate Entries

nadiana - October 10, 2007 - 15:06

You can avoid duplicated entries by adding "distinct"

$sql = "SELECT distinct n.title, n.nid FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid WHERE tn.tid in ($terms) AND n.status=1 ORDER BY n.created DESC";

Version 6.

DrupalDummy - November 9, 2008 - 14:52

It worked in Version 6 with if (db_result($result))

Can someone please tell me how I can print teasers under each title in the above code?

Thanks.

use node_load

adisetiawan - November 18, 2008 - 02:46

something like

<?php
if (db_result($result)) {
  while (
$data = db_fetch_object($result)) {
   
$node = node_load($data->nid);
   
//format this result array as you want
    
print_r($node);
  }
}
?>

Adi Setiawan
--------------
http://ex3me.org

Why this PHP block snippet can't display the last node?

hplc - March 13, 2009 - 13:55

The newest node posted can't be display by this PHP block snippet, while the others are ok?

Why?

My Drupal version is 6.10

Solved the last node display problem

hplc - March 13, 2009 - 23:57

As DrupalDummy said using: if (db_result($result)) in Drupal 6.10
But it can't display all the newest node, the newest node can't display.

So I changed the line to:
if ($result)

This works!

Text after PHP Snippet?

morisy - July 2, 2009 - 15:30

Plugged it into a block and it worked beautifully. Thanks to all the community members who tweaked it!

I wanted to padded it with some before and after text:

blah blah blah:

  • Piece 1
  • Piece 2
  • Piece 3

Blah blah.

But no matter what I do, the text after piece 3 fails to display. Is this a drawback of using PHP snippets? Is there something in this particular snippet that renders the next moot?

 
 

Drupal is a registered trademark of Dries Buytaert.