Drupal 9: How to query nodes by field or properties programatically

By Fernando Katsukawa, 4 November, 2022

This should also work for Drupal 8 and Drupal 10 versions.

To query nodes by some field or property in Drupal 9 is very simple, just put and run the following lines in your project.

use \Drupal\node\Entity\Node; 

// Get all node ids using entityQuery.
$nids = \Drupal::entityQuery('node')
  ->condition('status', 1)
  ->condition('type', 'article')
  ->sort('created', 'DESC');

// Get all node objects using node ids.
$nodes = Node::loadMultiple($nids);

// Perform actions for each node.
foreach($nodes as $node) {
  $node->set('title', 'My Title');

// Save node.

About the Author

Profile picture for user fkatsukawa

Fernando Katsukawa is a certified senior backend developer, who have been worked with Drupal in the last 12 years and counting...

Saved your precious time? Use the cup below to buy me a coffee!
buy me a coffee - cup