0

I want to display the number of unpublished comments in a template. I don't want to execute unnecessary queries on the database. Is there an already available function for this that I can use in page.tpl.php?

function comment_count_unpublished() {
  $count = db_query('SELECT COUNT(cid) FROM {comment} WHERE status = :status', array(
    ':status' => COMMENT_NOT_PUBLISHED,
  ))->fetchField();
  return t('Unapproved comments (@count)', array('@count' => $count));
}
1

I don't think there's anything already in page.tpl.php but it really depends on what is happening in the preprocessor(s) of your theme. I don't know what theme you're using.

If you're worried about calling a function like comment_count_unpublished() multiple times in one page load why not statically cache the result with drupal_static()?

Have you actually profiled that query and shown that it will cause problems on your site? Drupal generally runs hundreds of queries each page load so I don't think counting the unpublished comments in that table would have a noticeable impact on most sites.

2
  • I'm using (a custom version of) the Bootstrap theme. I just wanted to make sure, that there isn't a function that I'm unaware of. Otherwise, I can of course add it in the template.php. Performance won't be an issue, I'll use it only for admins.
    – cateye
    Jan 19 '13 at 15:06
  • I would say that if comment_count_unpublished() is running a query directly that there isn't one. Drupal core is usually pretty good at using its own API where appropriate. Jan 20 '13 at 5:38

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.