Drupal 9: Function To Find Nodes That Contain A Specific Block In Layout Config

/**
 * Find all nodes that contain a specific block in their layout config.
 *
 * @param string $blockName
 *   The ID of the block
 *
 * @return array
 *   The array of nodes.
 */
function findNodesByLayoutBlock($blockName) {
  $query = \Drupal::database()
    ->select('node__layout_builder__layout', 'n');
  $query->fields('n', ['entity_id', 'layout_builder__layout_section']);
  $results = $query->execute()->fetchAll();

  $nodes = [];

  foreach ($results as $result) {
    $layout = $result->layout_builder__layout_section;
    $layout = unserialize($layout);
    $components = $layout->getComponents();
    foreach ($components as $component) {
      if ($blockName === $component->getPluginId()) {
        $nodes[] = $result->entity_id;
      }
    }
  }

  return $nodes;
}

Note: Be wary of using on sites with lots of nodes.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
3 + 1 =
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.