18

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.

36

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);
  • 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
  • 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
13

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

$values = [
  'type' => 'page'
];
$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadByProperties($values);
7

Usually you need published nodes, not all.

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

Its actually very easy,

Drupal::entityTypeManager->getStorage('node')
  ->loadByProperties(['type' => 'content_type', 'status' => 1])

If you would like all nodes also unpublished just use:

Drupal::entityTypeManager->getStorage('node')
  ->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.