[Drupal 7] How to add next and previous navigation links to switch between contents

| | 2 min read

If you want to switch among contents or nodes in Drupal 7 website, you can do this by adding navigation links(PREV and NEXT) to that particular content. This will help you to see contents without going to any other link. There are contributed modules in Drupal for this but if you want to know how this can be created programmatically, read on.

As th primary step, implement node_preprocess hook, using which we can create two links "PREV" and "NEXT" to navigate through each content type.

Inside the MYMODULE_node_preproces write

$node_data = node_load($variables['node']->nid);
  $query = db_select('node', 'n');
  $query->fields('n', array('nid'))
    ->condition('type', $node_data->type)
    ->orderBy('nid'); 
  $result = $query->execute();
  $nids = array();
  while ($record = $result->fetchAssoc()) {
    $nids[] .= $record['nid'];
}

You can get node id by using the "$variables" array.

$current_node_id = $variables['node']->nid;

By using current node id you can get the current node key as well as pervious and next keys in that array.

To get current key you can use array_search function.

$current_node_key =  array_search($current_node_id, $myarray)

Here $myarray should be an array of nodes from nodes table. But you must select these content(node)
from node table only if content type is match with current content type.

From the $current_node_key you can find the previous and next key.

If the "$current_node_key - 1" is not less than zero.

$previous = $myarray[$current_node_key - 1]

and

If $current_node_key + 1 != sizeof($myarray)

$next = $myarray[$current_node_key + 1]

Here you should check the above conditions because when there is no previous and next content it may show some error.

Now you have to make two links(PREV and NEXT) in a node page where $variables['view_mode'] is 'full'.Here is an example,

$variables['content']['link'] = array(
  '#weight' => 999,
);
if (($current_node_key) != 0) {
  $variables['content']['link']['PREV'] = array(
    '#type' => 'link',
    '#prefix' => '',
    '#title' => t('PREV'),
    '#href' => "node/$previous",
    '#suffix' => '',
  );
}
if (($current_node_key + 1) != sizeof($myarray)) {
  $variables['content']['link']['NEXT'] = array(
   '#type' => 'link',
   '#prefix' => '',
    '#title' => t('NEXT'),
    '#href' => "node/$next",
    '#suffix' => '',
  );
}

You can also create an admin settings to list all the content types and select content types that you
want to enable this navigation links. To list all the content types you can use node_type_get_types() function. You can also use a custom table to save all the selected content types and apply the navigation links only to those content type you are selected

The modules which are already there one is this and another one is flippy. I hope this was help full. Thank you.