I want to write a function inside a module that will return last 20 contents of type X . is there any drupal ready function ? or shall i use queries ?


4 Answers 4


You'll want to make use of the db_query_range() and node_load_multiple() functions:

$args = array(':type' => $content_type);
$sql = 'SELECT nid FROM {node} WHERE status = 1 AND type  = :type ORDER BY created DESC';
$nids = db_query_range($sql, 0, 20, $args)->fetchCol();

$nodes = node_load_multiple($nids);
foreach ($nodes as $node) {
  // ...

You can use views to get that.

Make sure you sort items descending and limit the result number to be 20.

  • Dear down voter, Please specify reason for down voting so we can learn. thanks
    – saadlulu
    Sep 30, 2012 at 12:29

There is no special function for that, so you have to use the query.
This will fetch you last 20 published NIDs of a specific content type, which you can after load as node objects.

$last_20_nodes = db_query("SELECT `nid` FROM {node} WHERE `type` = :content_type AND `status` = 1 ORDER BY `created` DESC LIMIT 0, 20", array(':content_type' => 'YOUR CONTENT TYPE'));
foreach ($last_20_nodes as $last_node) {
  // Load the node object.
  $node = node_load($last_node->nid);
  // Continue with your process.
  // To see available properties and values, do a dpm($node).

Update: as Clive noted below, this might result in a lot of queries to possibly get just a few fields. Depending on your exact needs, it might be better to fetch only fields you need, rather than loading the nodes.

  • 1
    That will result in a lot of unnecessary db overhead, it's much better to use node_load_multiple()
    – Clive
    Sep 30, 2012 at 14:29

For Drupal 8 or 9 you can make use of entityQuery, as seen in the following code.

$query = \Drupal::entityQuery('node');
$query->condition('status', 1)
  ->condition('type', 'content_type')
$entity_ids = $query->execute();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.