I only know the title of a node, and I want to load the node using node_load()
.
How do I do that?
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));
}
node_load()
. Have edited question tag to reflect this.
$conditions
parameter): $nodes = node_load_multiple(array(), array('title' => 'node 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'])));
}
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
@todo Remove $conditions in Drupal 8.
node_load_multiple()
is a Boolean value telling Drupal to reset the internal cache used for the loaded entities.
EntityFieldQuery
class would require changes to port the code to Drupal 8.
In Drupal 7, you can use code similar to the following one.
$result = db_query("SELECT n.nid FROM {node} n WHERE n.title = :title AND n.type = :type", array(":title"=> $title, ":type"=> $type));
$nid = $result->fetchField();
In Drupal 8, run this:
$nodes = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties(['title' => $title]);
foreach ( $nodes as $node ) {
$node->doSomething(...);
}
$node
will be a fully instantiated node object.
Also in Drupal 8
$nids = \Drupal::entityQuery('node')
->condition('title', 'YourNodeTitle')
->sort('nid', 'DESC')
->execute();
and next:
$node = \Drupal\node\Entity\Node::load(HEREYOUNODEID);
Dont forget you need
use Drupal\node\Entity\Node;
arg(1)
it will be node/X for all pages. andnode_load()
works on only NID