Drupal - How to load a node based on its title?

In Drupal 7, the parameters for node_load() has been changed. To get the nodes that match some conditions, you should use the EntityFieldQuery class.

$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'])));
  }

In Drupal 6, you can use the following code.

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

If you know the node's type as well, then you can use the following code.

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

node_load() always returns a single node. That is because the function doesn't loop over the database query result resource returned from db_query().

  if ($revision) {
    array_unshift($arguments, $revision);
    $node = db_fetch_object(db_query('SELECT ' . $fields . ' FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.nid = n.nid AND r.vid = %d WHERE ' . $cond, $arguments));
  }
  else {
    $node = db_fetch_object(db_query('SELECT ' . $fields . ' FROM {node} n INNER JOIN {users} u ON u.uid = n.uid INNER JOIN {node_revisions} r ON r.vid = n.vid WHERE ' . $cond, $arguments));
  }

Drupal 7

Here is a simpler way (as already suggested by Clive and at SO):

$nodes = node_load_multiple(NULL, array("title" => "Foo Bar"));
$node = current($nodes);

and much easier to remember than using EntityFieldQuery class.

See also: Programmatically getting nodes by title in Drupal 7 at SO

Tags:

Nodes