Getting DISQUS comment count

Growler picture Growler · Apr 18, 2013 · Viewed 10.8k times · Source

I'm trying to get the comment count from a comic on my comics website. For example, comic id 66 has 2 comments. I'd like to get that count and display it on another page. So far when I follow the disqus guide below, it gives me a link to the comic with the comments, but doesn't give me the total comments.

DISQUS says...

Append #disqus_thread to the href attribute in your links. This will tell Disqus which links to look up and return the comment count. For example: <a href="http://foo.com/bar.html#disqus_thread">Link</a>.


But how would I get that count if my URL string was like this:

<a href=".?action=viewimage&site=comics&id=66">Link</a>

So my questions are:

  • Where would I append #disqus_thread?

  • How can I get the comments count from that one comic URL and display those total comments on another page?

Answer

Murali Bala picture Murali Bala · Jan 13, 2014

Example here: http://help.disqus.com/customer/portal/articles/1131783-tutorial-get-comment-counts-with-the-api

Variables

<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
  var disqusPublicKey = "YOUR_PUBLIC_KEY";
  var disqusShortname = "thenextweb"; // Replace with your own shortname

  var urlArray = [];
});
</script>

var urlArray = [];
//...continued from above

$('.count-comments').each(function () {
  var url = $(this).attr('data-disqus-url');
  urlArray.push('link:' + url);
});

Making the API Request

$('#get-counts-button').click(function () {
  $.ajax({
    type: 'GET',
    url: "https://disqus.com/api/3.0/threads/set.jsonp",
    data: { api_key: disqusPublicKey, forum : disqusShortname, thread : urlArray },
    cache: false,
    dataType: 'jsonp',
    success: function (result) {

      for (var i in result.response) {

        var countText = " comments";
        var count = result.response[i].posts;

        if (count == 1)
          countText = " comment";

        $('div[data-disqus-url="' + result.response[i].link + '"]').html('<h4>' + count + countText + '</h4>');

      }
    }
  });
});