Drupal 7 – Get the prev and next node ID using Previous/Next API

For developers, the Flippy module which i mentioned might be not flexible enough.
Drupal 7 – Display Previous and Next node links on node view using Flippy module

Then you could consider another module called Previous/Next API. With this module, you can add the previous and next node links in any preprocess functions, template.php or module files using the API functions provided by this module.

Another advantage is that it caches all the links in its own database table which could speed up the query and this also reduces the database loading. Let’s see how this module work.

1. Download and enable the module.

 

2. Go to the configuration page @ admin/config/system/prev_next. In this example, i only enable the index for the article content type. The index order currently can be set to node ID, node title, post date or update date.

 

3. Run Drupal Cron to start indexing.

 

4. If u have access to the database, you can see how the nodes are indexed.

 

5. So how could we add those links on the node view page? The most straight forward way is to create the following function in the theme template.php and we call this function to retrieve the link in the any .tpl.php.
template.php

function pn_node($node, $mode = 'n') {
  if (!function_exists('prev_next_nid')) {
    return NULL;
  }

  switch($mode) {
    case 'p':
      $n_nid = prev_next_nid($node->nid, 'prev');
      $link_text = 'previous';
      break;

    case 'n':
      $n_nid = prev_next_nid($node->nid, 'next');
      $link_text = 'next';
      break;

    default:
      return NULL;
  }

  if ($n_nid) {
    $n_node = node_load($n_nid);
    $html = l($link_text, "node/$n_nid", array('html' => TRUE));
    return $html;
  }
}

 

6. And add the following code to anywhere you want in the node-article.tpl.php.
node-article.tpl.php

<div id="node-nav">
  <ul>
    <li class="next"><?php print pn_node($node, 'n'); ?></li>
    <li class="prev"><?php print pn_node($node, 'p'); ?></li>
  </ul>
</div>

 

7. Check it out in the node view page.

 

Done =)

Reference: Drupal module – Previous/Next API

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.