Views has a setting to exclude the current nid from the URL from the listing one is currently viewing. This is essential when you have, say, a list of related nodes that are are defined by a category that includes the current node. If you don't exclude the current node, your current node will be listed in the "related content" block on itself. Well, obviously one is related to oneself, one thinks.
First, I tired to accomplish this through the UI with these steps, below.
- Add contextual filter:
- Get content ID from URL:
- Exclude results:
Perfect!
Except, wait. It's not working. Why? I have no idea.
But this works:
/** * Implements hook_views_query_alter */ function mymodule_views_query_alter($view, $query) { if ($view->id() == 'myview' && $view->current_display == 'mydisplay') { // Filter out the nid from the arg. if ($node = \Drupal::routeMatch()->getParameter('node')) { $query->addWhere(0, 'nid', array((int)$node->id()), 'NOT IN'); } } }