Get the latest 10 articles on a specified node type?
drupal, drupal-7, php
Solution
The code can be something like that (using db_select())
$query = db_select("node", "n") // select from the node table
->fields("n", array("nid", "title")) // fields nid, title
->condition("type", "page", "=") // where the node type = page
->orderBy("created", "DESC") // order by the newest
->range(0, 10) // select only 10 records
->execute(); // execute the query
while($record = $query->fetchAssoc()) {
print(l($record['title'], "node/" . $record['nid'])); // print the node title linked to node.
}
Another example using EntityFieldQuery():
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'club')
->propertyOrderBy("created", "DESC")
->range(0, 10)
->execute();
foreach($entities['node'] as $obj)
{
$node = node_load($obj->nid);
print(l($node->title, "node/" . $node->nid));
}
Performance wise: use the first method.
Problem
now, if the node type is article. on the term page's left, i want to show the latest 10 articles's title which node type is article. i don't want to use views, how do i do? thank you. if i want to show the latest 10 articles's title which node type is article on the node page's left . how to write the query. many thanks. ps:i found EntityFieldQuery maybe can do this, but i don't now how to do out put it. my code: ``` $query = new EntityFieldQuery(); $query ->entityCondition('entity_type', 'node') ->entityCondition('bundle', 'article') ->propertyCondition('status', 1) ->propertyOrderBy('created', 'DESC') ->range(0, 10); $result = $query->execute(); ```