Creating a paged list of nodes from a taxonomy category, with teasers.

Last modified: June 20, 2009 - 17:33

Note from the moderator: Thank you for sharing the snippet with the Drupal community. As it is now the snippet might present security risks. See Writing secure code for a background on the most common mistakes.

Specifically, the snippet

You may be interested in the functions node_view and/or check_markup.

The following code will generate a list of nodes, using the titles as links and showing a custom-length teaser (can be either shorter or longer than the drupal default).

<?php
/* Variables here include:
// $list_length:
//  the amount of nodes shown on one page
// $tid:
//  the number of the taxonomy category you want to display the nodes of
// $teaser_length:
//  the _minimum_ length of the teaser. Specify a number for a custom teaser length.
*/

 
$list_length = 5;
 
$tid = 11;
 
$teaser_length = 150;

 
$query = "SELECT n.nid" .
          
" FROM {node} AS n" .
          
" LEFT JOIN {term_node} AS tn ON n.nid = tn.nid" .
          
" WHERE n.status = 1" .
          
" AND tn.tid = $tid" .
          
" ORDER BY n.nid DESC";

 
$result = pager_query($query, $list_length);

 
$output = "<div id='node-list'><ul>";
  while (
$item = db_fetch_object($result)) {
   
$node = node_load($item->nid);
   
$output .= '<li><h4>' . l($node->title, "node/" . $node->nid) .
     
'</h4><p>' . node_teaser($node->teaser, $teaser_length) . '</p></li>';
  }
 
$output .= "</ul></div>";
  print
$output;
  print
theme('pager', $list_length, 0, 0);
?>

an alternate method is:

<?php
/* Variables here include:
// $list_length:
//  the amount of nodes shown on one page
// $tid:
//  the number of the taxonomy category you want to display the nodes of
// $teaser_length:
//  the _minimum_ length of the teaser. Specify a number for a custom teaser length.
*/

 
$list_length = 5;
 
$tid = "1";
 
$teaser_length = 150;

 
$query = "SELECT tn.tid, n.nid" .
         
" FROM {node} AS n" .
         
" LEFT JOIN {term_node} AS tn ON n.nid = tn.nid" .
         
" WHERE n.status = 1" .
         
" AND tn.tid IN ($tid)" .
         
" ORDER BY n.nid DESC";

 
$result = pager_query($query, $list_length);

 
$output = "<div id='node-list'><ul>";
  while (
$item = db_fetch_object($result)) {
   
$aNode['nid'] = $item->nid;
   
$node = node_load($aNode);
   
$output .= '<li><h4>' . l($node->title, "node/" . $node->nid) .
     
'</h4><p>' . node_teaser($node->teaser, $teaser_length) . '</p></li>';
  }
 
$output .= "</ul></div>";
  if (
db_num_rows($result) < $list_length)
   
$list_length = db_num_rows($result);

  print
$output;
  print
theme('pager', $list_length);
?>

 
 

Drupal is a registered trademark of Dries Buytaert.