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.
CAPTCHA
2 + 16 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.