Drupal 10: Load A Random Node From The Database

Entity type manager doesn't have access to the random order so we need to use a query to find the node ID and then load it using entity type manager.

$select = \Drupal::database()->select('node_field_data', 'n')
  ->fields('n', ['nid', 'title'])
  ->condition('n.status', 1)
  ->range(0, 1)
  ->orderRandom();

$results = $select->execute();
$nid = $results->fetchField();

$node = \Drupal::service('entity_type.manager')->getStorage('node')->load($nid);

Add new comment

The content of this field is kept private and will not be shown publicly.