Get node title without loading the whole node object

Public

If you feel bad loading the whole node object just to get the title out use this helper function.

</> CopyGet raw version
php
  1. /**
  2.  * Helper function to get the node title without loading the whole node object.
  3.  */
  4. function get_node_title($nid) {
  5. return db_query('SELECT title FROM {node} WHERE nid = :nid', array(':nid' => $nid))->fetchField();
  6. }

Comments

Charles Toepfer's picture

If you have a set of nodes, a single query might be faster ...

$query = new EntityFieldQuery();
$bundle = 'article';
$query->entityCondition('entity_type', 'node')->entityCondition('bundle', $bundle);
$results = $query->execute();
$ids = $results['node'];
$query = db_select('node', 'n')->fields('n', array(
'nid',
'title'
));
$db_or = db_or();
foreach (array_keys($ids) as $nid) {
$db_or->condition('n.nid', $nid, '=');
}
$query->condition($db_or);
$titles = $query->execute()->fetchAll();

Elin Yordanov's picture

@CharlesToepfer
You don't need to loop through the $nids, you can use it like follows:

  1. $ids = array_keys($results['node']);
  2. $query = db_select('node', 'n')
  3. ->fields('n', array('nid', 'title'))
  4. ->condition('n.nid', $ids, 'IN');
  5. $titles = $query->execute()->fetchAll();