How to Load a Node Programmatically by Title in Drupal?

By | 02nd Mar 2022 | 1 min read

As we know, all content in Drupal is treated as a node. We can load a node entity by ID, but how can one load a node based on its title? Let's check how:

It is interesting to see how Drupal improves overtime on this.

In Drupal 6, it was just node_load.

$node = node_load(array('title' => 'node title'));

If you know the node's type as well, then you can use the following code.  For example, if the node type is an article then we can use the below  code

$node = node_load(array('title' => 'node title', 'type' => 'article'));

In Drupal 7, node_load is still there, but you need to use EntityFieldQuery class to fetch the node you want for a specific title.

$query = new EntityFieldQuery();


 $entities = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'your_node_type')
  ->propertyCondition('title', 'your node title')
  ->propertyCondition('status', 1)
  ->range(0,1)
  ->execute();

  if (!empty($entities['node'])) {
    $node = node_load(array_shift(array_keys($entities['node'])));
  }

For Drupal 8 and 9, we can use the below code to get the node based on the title

$nids = \Drupal::entityQuery('node')
->condition('title', 'YourNodeTitle')
->sort('nid', 'DESC')
->execute();

and next:

$node = \Drupal\node\Entity\Node::load($nids);

Also, you will need :

use Drupal\node\Entity\Node;

These are some of the simplest ways to get a node based on its title.

Reference

https://drupal.stackexchange.com/questions/5955/how-to-load-a-node-based-on-its-title