PREV NEXT links for nodes in circular way

PREV NEXT links for nodes in circular way

Categories:

This is just a sample of how you can add PREV NEXT links to your node type template. This function generates links to navigate your nodes in alphabetical order ASC.

Paste this code in your template.php file:

<?php
/**
* ARRAY SEARCH
*/
function multiarray_search($arrayVet, $campo, $valor){
    while(isset(
$arrayVet[key($arrayVet)])){
        if(
$arrayVet[key($arrayVet)][$campo] == $valor){
            return
key($arrayVet);
        }
       
next($arrayVet);
    }
    return
false;
}

/**
* SIMPLE NEXT PREV BY NODE TYPE
*/
function prev_next_type($id = 1, $direction = 'next', $label = 'next') {
 
$output = NULL;
 
 
$type = db_result(db_query("SELECT n.type FROM {node} n WHERE n.nid = %d",$id));
 
$result = db_query("SELECT n.nid, n.title FROM {node} n WHERE n.type = '%s' ORDER BY n.title ASC", $type);
 
  while (
$row = db_fetch_array($result)) {
   
$all_nodes[] = $row;
  }
 
 
$key = multiarray_search($all_nodes,'nid',$id);

 
$nid = $direction == 'prev' ? $all_nodes[$key-1]['nid'] : $all_nodes[$key+1]['nid'];
 
$text = $direction == 'prev' ? $all_nodes[$key-1]['title'] : $all_nodes[$key+1]['title'];

  if (
$nid == null) {
      if (
$direction == 'prev'){
       
$nid = $all_nodes[sizeof($all_nodes)-1]['nid'];
       
$text = $all_nodes[sizeof($all_nodes)-1]['title'];
      }else {
       
$nid = $all_nodes[0]['nid'];
       
$text= $all_nodes[0]['title'];   
        }
  }

 
$output = l($label"node/".$nid);
 
  return
$output;
}
?>

Paste this code into your node-yourtype.tpl.php file:

<div class="recipe-prev-next">
<div class="recipe-prev"><?php print prev_next_type($nid, $direction = 'prev', $label = 'PREVIOUS'); ?></div>
<div class="recipe-next"><?php print prev_next_type($nid, $direction = 'next', $label = 'NEXT'); ?></div>
</div>

Hello, Pedro, Very useful

Hello, Pedro,

Very useful snippet, but for most cases
don't forget to include only published nodes,
that is add 'WHERE n.status = 1' to queries

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
7 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.