Next/Previous with images by date

Last modified: August 26, 2009 - 23:13

When you display all the images in a gallery they are showed sorted by date, the newest is first. This is also how the prev/next buttons should take you.

In most cases, for new galleries, sorting by date or nid probably will give the same result since you get increasing dates and increasing node ids as you keep adding images.

If you edit an image and if you change the date (Authored on) the you will start running into problems. Here is the code I used to properly navigate by date (and this code also fixes the DESC/ASC sort order):

<?php
function next_prev($current_nid, $type, $btn_type, $label, $class) {
  
$query = db_query("SELECT tid FROM {term_node} WHERE nid = $current_nid;");
  
$tid = db_result($query);
  
$query = db_query("SELECT created FROM {node} WHERE nid = $current_nid");
  
$current_created = db_result($query);
  
$sql = "SELECT n.nid, n.title FROM {node} n INNER JOIN {term_node} t ON n.nid = t.nid ";
  
$sql .= "INNER JOIN {term_data} r ON t.tid = r.tid WHERE n.type = '".$type."' AND n.created ";
   switch (
$btn_type) {
        case
"next":
               
$sql .= "< ";
               
$sort = "DESC";
                break;
        case
"prev":
               
$sql .= "> ";
               
$sort = "ASC";
                break;
        default:
                return
NULL;
                break;
   }
  
$sql .= $current_created ." AND r.tid = ". $tid ." AND n.status = 1 ORDER BY n.created $sort;";
  
$query = db_query($sql);
  
$result = db_fetch_array($query);
   if (!
$result) {
       
$query = db_query("SELECT name FROM {term_data} WHERE tid = $tid;");
       
$name = db_result($query);
     return
l("Back To $name", "$type/tid/$tid", array("title" => $name, "class" => $class));
   } else {
     return
l($label, "node/".$result['nid'], array("title" => $label, "class" => $class));
   }
}
?>

 
 

Drupal is a registered trademark of Dries Buytaert.