39

I am looking for a snippet that lets me display the total count for a specific node type, e.g. "Pages = 167" or "Products = 10630."

What code should I use to achieve this?

34

Here is a function that will return the number of nodes for a specific content type:

function YOURTHEME_get_node_count($content_type) {
  $query = 'SELECT COUNT(*) ' .
           'FROM {node} n ' .
           'WHERE n.type = :type';
  return db_query($query, array(
      ':type' => $content_type
  ))->fetchField();
}

To use this code in your theme, add the function into your template.php and then you can call the function like this:

echo 'Pages: ' . YOURTHEME_get_node_count('page');
echo 'Products: ' . YOURTHEME_get_node_count('product');
56

You can use the Views module to do this.

  1. Create a new view, remove sort options, fields and other default settings
  2. Add a field for "Content: Type"
  3. Expand the "advanced" part on the right and set "Use aggregation" to "Yes"
  4. Add yet another field for "Content: Type"
  5. On the second "Content: Type" field, click "Aggregation settings"
  6. Set the aggregation type to "count"
  7. The second "Content: Type" should now look like "COUNT(Content: Type)"

That should be it! If needed, adjust some more settings like field labels and row style settings.

Here is an export of such a view, so you can easily import it and try it out:

$view = new view;
$view->name = 'nodecounts';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Node counts';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Node counts';
$handler->display->display_options['group_by'] = TRUE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['inline'] = array(
  'type_1' => 'type_1',
  'type' => 'type',
);
$handler->display->display_options['row_options']['separator'] = ': ';
$handler->display->display_options['row_options']['hide_empty'] = 0;
$handler->display->display_options['row_options']['default_field_elements'] = 1;
/* Field: Content: Type */
$handler->display->display_options['fields']['type_1']['id'] = 'type_1';
$handler->display->display_options['fields']['type_1']['table'] = 'node';
$handler->display->display_options['fields']['type_1']['field'] = 'type';
$handler->display->display_options['fields']['type_1']['label'] = '';
$handler->display->display_options['fields']['type_1']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['external'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['type_1']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['type_1']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['trim'] = 0;
$handler->display->display_options['fields']['type_1']['alter']['html'] = 0;
$handler->display->display_options['fields']['type_1']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type_1']['element_default_classes'] = 1;
$handler->display->display_options['fields']['type_1']['hide_empty'] = 0;
$handler->display->display_options['fields']['type_1']['empty_zero'] = 0;
$handler->display->display_options['fields']['type_1']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['type_1']['link_to_node'] = 0;
$handler->display->display_options['fields']['type_1']['machine_name'] = 0;
/* Field: COUNT(Content: Type) */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'node';
$handler->display->display_options['fields']['type']['field'] = 'type';
$handler->display->display_options['fields']['type']['group_type'] = 'count';
$handler->display->display_options['fields']['type']['label'] = '';
$handler->display->display_options['fields']['type']['alter']['alter_text'] = 0;
$handler->display->display_options['fields']['type']['alter']['make_link'] = 0;
$handler->display->display_options['fields']['type']['alter']['absolute'] = 0;
$handler->display->display_options['fields']['type']['alter']['external'] = 0;
$handler->display->display_options['fields']['type']['alter']['replace_spaces'] = 0;
$handler->display->display_options['fields']['type']['alter']['trim_whitespace'] = 0;
$handler->display->display_options['fields']['type']['alter']['nl2br'] = 0;
$handler->display->display_options['fields']['type']['alter']['word_boundary'] = 1;
$handler->display->display_options['fields']['type']['alter']['ellipsis'] = 1;
$handler->display->display_options['fields']['type']['alter']['strip_tags'] = 0;
$handler->display->display_options['fields']['type']['alter']['trim'] = 0;
$handler->display->display_options['fields']['type']['alter']['html'] = 0;
$handler->display->display_options['fields']['type']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['type']['element_default_classes'] = 1;
$handler->display->display_options['fields']['type']['hide_empty'] = 0;
$handler->display->display_options['fields']['type']['empty_zero'] = 0;
$handler->display->display_options['fields']['type']['hide_alter_empty'] = 1;
$handler->display->display_options['fields']['type']['separator'] = '';
$handler->display->display_options['fields']['type']['format_plural'] = 0;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block');
  • That's looks to "heavy" for the server performance. – Fedir RYKHTIK Nov 22 '11 at 6:29
  • 7
    @Fedir, if you think that, you need to learn more about the Views module. This is just exported configuration and setting properties on an object is not heavy on the server at all. It is true that the Views module as a whole will use more resources than a custom block, but it's nothing that the smallest shared server couldn't handle. There are good reasons to use views throughout your site: maintainability, security, faster development and caching options. Custom code is fine too, but do not discard Views just because an export takes 81 lines. – marcvangend Nov 22 '11 at 8:29
  • 3
    I'm agree, the Views module could be quite useful in many situations. For current task, I'll use simple query to count the object, as it will be lighter. I don't like to overhead where I could it faster. – Fedir RYKHTIK Nov 22 '11 at 9:35
11

The preferred, programmatic way, is to use the EntityFieldQuery class. Learn why EntityFieldQuery is superior to db_query().

Here's an example of counting Nodes of type Blog.

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node') // grab nodes
->entityCondition('bundle', 'blog') // filter by blog type
->propertyCondition('status', 1) // filter by published
->count(); // count

$result = $query->execute();

See similar question.

7

I did this using EntityFieldQuery.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
    /* this is the content type machine name */
    ->entityCondition('bundle', 'product')
    /* You can set extra properties using fieldCondition and properties with propertyCondition */
    ->fieldCondition('field_product_status', 'tid', key(taxonomy_get_term_by_name('New')))
    ;

$result = $query->execute();
if (isset($result['node'])){
    $count_of_new_product_nodes = count($result['node']); 
}
  • 3
    EntityFieldQuery unfortunately will have to fetch all the nodes from the databases and then count how many are there. So this is really heavy. Use the views or the SQL answers above they're much lighter. – Mario Awad May 8 '14 at 10:21
5

Using Drush is simple and quick.

drush sqlq 'select count(node.nid) as node_count, node_type.type from node inner join node_type on node.type = node_type.type group by node_type.type'

This gives output similar to:

node_count  type
17  category_2012
20  category_2013
19  category_2014
3   competition
19  entry_2012_breakthrough
89  entry_2012_digitalother
50  entry_2012_directdirect
19  entry_2012_filmsecscn
17  entry_2012_insights
12  entry_2012_outdoor
31  entry_2012_promo
19  entry_2013_breakthrough
100 entry_2013_digitalother
40  entry_2013_directdirect

And then if you want filter by a specific type, just use grep like this:

drush sqlq 'select count(node.nid) as node_count, node_type.type from node inner join node_type on node.type = node_type.type group by node_type.type' | grep 2014
3

For anyone who is interested, another solution is to use the countQuery method of the SelectQuery class (via db_select).

$count = db_select('node')
  ->condition('type', 'some-type')
  ->countQuery()->execute()->fetchField();

However, I do prefer the EntityFieldQuery solution posted by timofey. I am only providing this as a reasonably sensible alternative.

1
SELECT
  COUNT({node}.nid) AS node_count,
  {node_type}.type
FROM {node}
  INNER JOIN {node_type} ON {node}.type = {node_type}.type
GROUP BY {node_type}.type;

Use this query in your code

0

The Node Type count module do the same as you require.

This module is used to Show a count of nodes of a particular content-type and also number of Users of particular role type.

This module will be used for statistical and dev purposes only.

0

As a variation to the answer about using the Views module, you could "use" the view that comes with the Charts module. Simply install / enable it, no additional configuration, coding, etc needed. Some more details about this view, included in the Out-of-the-box examples (quote from this link):

... navigate to charts/examples/views in your site. You should then see a column chart and a pie chart, which are followed by a tabular display also. Both charts and the table display contain data about the total number of nodes for each of the available content types.

Notes:

  • As a bonus, apart from the tabular format, you also get a chart to visualise the number of nodes by content type.
  • If you like the view, and/or it is close to what you want, you might also clone the view, and then just disable the Charts module again.

Disclosure: I'm the maintainer of this module,
I hope this does not violate the site's policy on self-promotion.

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