Show Total Number of Disqus Comments of a Page in Drupal 7

On a recent project I had to show the total number of comments posted using Disqus for each node on a page. What the page did was loop through a bunch of nodes and render the teaser view of each node.  The teaser was shown by rendering node.tpl.php, and in that file I had to display the total number of comments. Clicking a teaser view took me to the full page of the node that also contained the Disqus commenting box.

To do this I had to do add code in two places:

First, I added the following code in my theme's template.php hook_preprocess_html. The code puts the required Disqus javascript snippet in the footer.  I replaced SHORTNAME with the short name I chose when I was configuring Disqus for my site:

function mytheme_preprocess_html(&$variables, $hook) {
 $disqus_js = "
  /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
  var disqus_shortname = 'SHORTNAME'; // required: replace example with your forum shortname

  /* * * DON'T EDIT BELOW THIS LINE * * */
  (function () {
   var s = document.createElement('script'); s.async = true;
   s.type = 'text/javascript';
   s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
   (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
  }());";
  
 drupal_add_js($disqus_js, 
  array(
   'type' => 'inline',
   'scope' => 'footer'
  )
 );
}

Second, I added the following <a> tag in node.tpl.php.  What's important is the hash #disqus_thread. The javascript above will look for links formatted this way and insert "5 comments" in the inner HTML of the tag.

<a href="<?php print url(drupal_get_path_alias('node/' . $node->nid));?>#disqus_thread"></a>

Technically the total comments can be shown in any template file as long as the Disqus javascript snippet and <a> tags are on the page.