Hi, I am looking for a way to simply display the number of nodes in a specified content type. Something like this:

print count_nodes('story');

I know this aint valid code, but you get the general idea.

I dont want any frills or specific sorting, I simply wana display a simple number of nodes in a specified content type.

Is this possible?

Thanks in Advance.

Comments

darklight’s picture

I have so far wrote a small, yeh very inefficient code that "works" but is so inneficient I am unwilling to use it on my live site. Surely there's a better way. Here's my current code:

$type = 'news';
$count = db_result(db_query("SELECT COUNT(*) FROM {node} WHERE type = '$type'"));
print $count;

I would be prepared to keep this code, if I only had to run the $count query once, and use the $type variable to specify the node-type for each "print $count" but I cant see any way of doing this. Any ideas?

grobemo’s picture

You beat me to it. Following the taxonomy_term_count_nodes model might help. How about this?

<?php

function count_nodes($type) {
  static $node_count;

  if (empty($node_count)) {
    $result = db_query('SELECT type, COUNT(nid) AS count FROM {node} GROUP BY type');
    while ($row = db_fetch_array($result)) {
      $node_count["{$row['type']}"] = $row['count'];
    }
  }

  return $node_count[$type];
}

?>

(If you're not familiar with static variables, you can read about static variables in the PHP manual.)

grobemo’s picture

Someone else might have a better way to do this, but here's the brute force way:

<?php
  print db_result(db_query('SELECT COUNT(nid) FROM {node} WHERE type = "%s"',$type));
?>

Assuming you want to be able to search for different node types, you'll need a way to specify $type. For instance, you could wrap this query in a function of its own, and pass the type as an argument:

<?php

function count_nodes($type) {
  return db_result(db_query('SELECT COUNT(nid) FROM {node} WHERE type = "%s"',$type));
}

?>

Of course, there's no error checking or anything like that in there. If you want that and don't know how to do it, just ask.

You may also want to check out the taxonomy_term_count_nodes function, though as far as I can tell, it only works for specific terms.

grobemo’s picture

Oops. You beat me to it. See my response to your comment #1 above.

darklight’s picture

Hey guys, thanks a lot!!! Grobemo, your code worked wonders!! I did not think of using functions :P thanks a lot guys, I reli appreciate this!