Creating Next/Previous node pager using Views in Drupal 8

Looking for a way to implement next/previous node pager in Drupal 8? There are some modules available like Pager for Content type which allows you to create next previous pager for nodes with some configurations. But what if you want to create a pager which lets you manage conditions for next or previous node to be displayed e.g. display by author or category? Here I am going to show you, how to create a pager which lets you manage conditions and display of the next and previous node.

Create a view

For creating a next/previous node pager, we need to create a view with block displays for next and previous pagers. Refer images shown below for previous node and next node displays of the view:

You can add as many conditions as you want for these views. The Content ID contextual filter added in the view needs default value as Content ID from URL and Excluded from the the result. Refer images shown below:

Create a module

Now create a custom module and add following code in .module file of your newly created module and make necessary changes to the code like changing module name, view name and display name.

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
function experiments_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($view->id() == 'pager' && $node) {
    $operator = $view->getDisplay()->display['id'] == 'next_node' ? '>=' : '<=';
    foreach ($query->where as &$condition_group) {
      array_push($condition_group['conditions'], [
        'field' => 'node_field_data.created '.$operator.' ' . $node->getCreatedTime(),
        'value' => [],
        'operator' => 'formula',

Enable the module and add blocks of next node and previous node pagers to the regions you want.

If you are using display suite module create block fields and add them to the node display.

That's it.

pagerviewsnextpreviousblockdrupal 8