I would like to get all nodes that are of my_custom_type type in Drupal 8.

I know I can get all the nodes (of any type) with \Drupal\node\Entity\Node::loadMultiple() and the list of all types by \Drupal\node\Entity\NodeType::loadMultiple().

But how to get only the nodes of given node type?

I really don't want to use specialized module for it (if it's possible), just keep it as simple as possible. I will use the solution in my custom module.

And loading all the nodes with \Drupal\node\Entity\Node::loadMultiple() and then check their type in foreach would hit the performance too much.


You can use Drupal::entityQuery() & Node::loadMultiple() to load all the nodes of your given type:

$nids = \Drupal::entityQuery('node')->condition('type','my_custom_type')->execute();
$nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);
  • 1
    Any way to do this generically for any entity type? You would think \Drupal::entityQuery($type)->condition('type',$bundle)>execute(); would work, but sadly no. – liquidcms Apr 14 at 19:47
  • 1
    This answer is specific to node entities. Details will change for other entities. You should ask another question for a general case. – Shawn Conn Apr 14 at 21:04
  • 2
    In OOP code this now is $nids = $this->entityTypeManager->getStorage('node')->getQuery()->condition('type','my_custom_type')->execute();. See drupal.org/node/2849874. – leymannx Oct 9 at 19:19

Another way to do this would be using this snippet of code:

$values = [
  'type' => 'page'
$nodes = \Drupal::entityTypeManager()

Usually you need published nodes, not all.

$nids = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->condition('type', 'YOUR-NODE-TYPE')
$nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

Its actually very easy,

  ->loadByProperties(['type' => 'content_type', 'status' => 1])

If you would like all nodes also unpublished just use:

  ->loadByProperties(['type' => 'content_type'])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.