Skip to content

Instantly share code, notes, and snippets.

@sun
Created February 28, 2018 20:31
Show Gist options
  • Save sun/479c7b4df18fd8429a41a7989edf331a to your computer and use it in GitHub Desktop.
Save sun/479c7b4df18fd8429a41a7989edf331a to your computer and use it in GitHub Desktop.
How to exclude nodes on a single page that were output in a previous view already?
<?php
/**
* Gets queried node IDs and store them in a static variable.
*
* Implements hook_views_post_execute().
*/
function custom_views_post_execute($view) {
if ($view->id() !== 'taxonomy_term') {
return;
}
$queried_nids = &drupal_static('custom_queried_nids', []);
$queried_nids = array_unique(array_merge($queried_nids, array_column($view->result, 'nid')));
}
/**
* Excludes already queried node IDs to prevent duplicate listings.
*
* Implements hook_views_query_alter().
*/
function custom_views_query_alter($view, $query) {
if ($view->id() !== 'taxonomy_term') {
return;
}
if ($queried_nids = drupal_static('custom_queried_nids', [])) {
$query->addWhere('AND', 'node_field_data.nid', $queried_nids, 'NOT IN');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment