0

I know there are easier ways to sort nodes by type, using views, or using:

$query->loadByProperties(['type' => 'my_content_type']);

... but what I really want to do is return ALL nodes and then do different things based on the type field, like so:

$result = \Drupal::entityQuery('node')->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($result);

foreach ( $nodes as $node ) {
  if ( $node->type == "my_content_type" ) {

    // do something...

  } else {

    // do something else...

  }
}

However, my condition is never getting met, so I can only conclude that I am referencing the node type incorrectly. What am I doing wrong?

  • 1
    $node->type is for Drupal 7, to get the content type name (bundle) use $node->bundle() instead like if ( $node->bundle() == "my_content_type" ) – berramou Sep 9 at 14:11
1

Thanks @berramou the solution is to use:

if ( $node->bundle() == "my_content_type" ) { ... }

Solved!

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.