1

How can I load recent nodes with node_load()?

I used the following code, but I can't edit the links because it creates a list where they are inside it. I want to load the node IDs, and then use node_load() to load each node.

$output = db_query_range(db_rewrite_sql("SELECT n.nid, n.title, n.created FROM {node} n WHERE n.type = '%s' AND n.status = 1 ORDER BY n.created DESC"), story, 0, 10));
print $output;

How is that possible?

1

Using only node_load() you cannot get a list of the most recent nodes, as node_load() returns a single node object for the node that matches some criteria; it's not a function that returns a list of nodes.

The faster, but a little inefficient, way to get a list of more recent nodes is to:

  • Get the list of node IDs associated with the most recent nodes
  • Call node_load() for each of the node IDs obtained from the first step

You could use code similar to the following one.

   $nodes = array();
   $result = db_query_range("SELECT n.nid FROM {node} n ORDER BY n.created DESC", array(), 0, $number_of_posts);

   while ($nid = db_result($result)) {
     $nodes[] = node_load($nid);
   }

After that code is executes, $nodes will contains the $number_of_poststh recent nodes.

  • Really Thanks, I tried this code but I couldn't get the result. maybe I'm missing something. can you make an example of showing list of nodes IDs ? – Zim3r Aug 4 '12 at 17:28
  • Did you define $number_of_posts? I tested the code, and it works. – kiamlaluno Aug 4 '12 at 17:35
  • Yes I did, I think I'm making a mistake somewhere. can you please tell me e.g. how to print all titles? Thanks – Zim3r Aug 4 '12 at 17:49
  • 1
    That works, but it is making the assumption newer nodes have a higher node ID; while that is generally true, it is not necessary true. I would rather join that database table with the node table. – kiamlaluno Aug 4 '12 at 19:14
  • 1
    SELECT DISTINCT(n.nid) FROM {node} n INNER JOIN {term_node} tn ON n.vid = tn.vid WHERE tn.tid = '1' AND n.status = 1 ORDER BY n.created DESC – kiamlaluno Aug 4 '12 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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