1

there are modules out there for my problem, but they are not stable and also i need to be able to manipulate the result so here we go:

i need to provide a block on a certain node type which offers a previous and next link to cycle through the nodes of the same content type.

how can i select the previous and next node programmatically using db_query() and then output the links to them?

thanks in advance for your help

2 Answers 2

0

You haven't provided any indication of the sort order you want so I'll guess at created date:

$prev_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created < :created LIMIT 1", array(':created' => $current_node->created))->fetchField();
$next_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created > :created LIMIT 1", array(':created' => $current_node->created))->fetchField();

if ($prev_nid > 0) {
  $prev_link = l('Previous', "node/$prev_nid");
}

if ($next_nid > 0) {
  $next_link = l('Previous', "node/$next_nid");
}

You'll need a reference to $current_node (i.e. the node relating to the current page). There are dozens of places you could put this code so I'll let you decide on that, but if you want an easy way to grab the node object associated with the node page you're on use this:

$current_node = menu_get_object();
if (isset($current_node->nid) && $current_nid > 0) {
  // We're on a node page and $current_node is a valid, loaded node object
}

Hope that helps

1
  • changed the code to suit my needs and am using it in my template.php now. you helped a lot, thanks!
    – maze
    Oct 5, 2011 at 10:20
1

Clive is right. But $prev_nid is looking for the first node in the table. So you could add an ORDER BY, like this:

$prev_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created < :created ORDER BY created DESC LIMIT 1", array(':created' => $node->created))->fetchField();
$next_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created > :created ORDER BY created LIMIT 1", array(':created' => $node->created))->fetchField();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.