This is a code snippet that shows how to remove all the node entities from entityqueue - lists that have "expired" nodes via a daterange field (field_banner_daterange).
use Drupal\node\Entity\Node;
use Drupal\entityqueue\Entity\EntityQueue;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\entityqueue\Entity\EntitySubqueue;
/**
* Removes old banners from entityqueue lists.
*/
function banner_sync_remove_old_banners() {
$entityTypeId = 'node';
$now = time();
// Get all the entity queues referencing the targets entity type.
$queues = EntityQueue::loadMultipleByTargetType($entityTypeId);
$queues = ['banners_desktop', 'banners_mobile'];
foreach ($queues as $queue_id) {
// Get all the subqueues which are referencing the above queues.
$query = \Drupal::entityQuery('entity_subqueue')
->condition('queue', $queue_id);
$result = $query->execute();
$subqueues = EntitySubqueue::loadMultiple($result);
// Check for expired banner entity in a subqueue.
foreach ($subqueues as $subqueue) {
$items = $subqueue->get('items')->getValue();
foreach ($items as $key => $item_data) {
$entity = Node::load($item_data['target_id']);
$endDate = $entity->get('field_banner_daterange')->end_value;
$endDateTimestamp = strtotime($endDate);
if ($endDateTimestamp <= $now) {
unset($items[$key]);
\Drupal::logger('banner_sync')->notice(
'Removed Banner: %title from banner list: %banner_list.',
[
'%title' => $entity->label(),
'%banner_list' => $queue_id
]
);
$subqueue->set('items', $items);
$subqueue->save();
}
}
}
}
}
You can add this as a cron job like this.
/**
* Implements hook_cron().
*/
function banner_sync_cron() {
banner_sync_remove_old_banners();
}