twitter

Recent Comments

David Boyer
David Boyer January 13, 2012 at 10:05AM
Is Your CFLOOP Hogging Memory or Causing OutOfMemory Errors?

Interesting to find that out, wouldn't have expected it to be a problem. I've had similar...

baljit dhanoa
baljit dhanoa January 12, 2012 at 9:08AM
Creating A Recent Comments Widget With Disqus's API and PHP

Creating A Recent Comments Widget With Disqus's API and PHP good code pls try

Web Hosting Provider
Web Hosting Provider January 10, 2012 at 5:23PM
Creating A Recent Comments Widget With Disqus's API and PHP

Superb and very informative for me,,,

web hosting
web hosting December 2, 2011 at 7:28AM
If PHP's file_get_contents Function is Failing With IIS 7

I am new guy for this PHP. i get it clear idea about your topic.All the points are explained...

Aaron J. White
Aaron J. White November 14, 2011 at 11:54PM
Creating A Recent Comments Widget With Disqus's API and PHP

If you want to put the number of posts in a different area than the recent comments section...

Aaron J. White
Aaron J. White November 14, 2011 at 10:10PM
Creating A Recent Comments Widget With Disqus's API and PHP

It depends, are you using wordpress or joomla? I have a different plugin that checks disqus for...

Yulia Novozhilova
Yulia Novozhilova November 14, 2011 at 4:22PM
Creating A Recent Comments Widget With Disqus's API and PHP

very cool... it works! Do you know if it is possible to include number of total post likes on...

Aaron J. White
Aaron J. White October 30, 2011 at 10:40AM
Creating A Recent Comments Widget With Disqus's API and PHP

Hmm...It would probably help if I post a comment on my site so people can actually see my...

Creating A Recent Comments Widget With Disqus's API and PHP

Posted: November 9th, 2011 - A few days ago I tried the default widget for recent comments that Diqus provides, but I just couldn't get it to look like I wanted it. Thus, I decided to look for a different solution and it wasn't long before I noticed the Disqus API. Now let me just say now that I think Disqus did a GREAT job with the creation of the documentation and examples for their api.

For each resource in the Disqus api their is a seperate page where you can send test request with parameters and view the output of the corresponding response. With that said , even with my very limited PHP knowledge it wasn't long before I had a working script. First I will show the whole script and then break it down. Note: You need to signup with Disqus and register a new application in order to use this script.

<?php
try {
 //Parameters  - Feel free to modify these
 $commentLimit = "15";
 $dateFormat='F j, Y \a\t g:iA';
 $commentLength=95;
 $apiVersion = "3.0";
 $resource = "posts/list";
 $outputType = "json";
 $publicKey = "YOUR_PUBLIC_KEY";
 $forumName = "YOUR_FORUM_NAME";
 // put style parameters in an array
 $styleParameter = array(
  "commentLimit" => $commentLimit,
  "dateFormat" => $dateFormat,
  "commentLength" => $commentLength
  );
 //put request parameters in an array
 $dqParameter = array(
  "api_key" => $publicKey,
  "forum" => $forumName,
  "include" => "approved",
  "limit" =>  $commentLimit,
  );
 //Create base request string
 $dqRequest ="http://disqus.com/api/".$apiVersion."/".$resource.".".$outputType;
 //add parameters to request string
 $dqRequest = addQueryStr($dqRequest, $dqParameter);
 // get response with finished request url
 $dqResponse = @file_get_contents($dqRequest);
 //check repsonse
 if($dqResponse !== false )
 {
  // convert response to php object
  $dqResponse = json_decode($dqResponse, true);
  // get comment items from response
  $dqComment = $dqResponse["response"];
  //check comment count
  if(count($dqComment) > 0)
  {
   echoComments(
       $dqComment,
       $publicKey,
       $styleParameter
      );
  }
  else
  {
   noComments();
  }
 }
 else
 {
  noComments();
 }

}
catch(Exception $e)
{
 noComments();
}

function echoComments(
      $comment,
      $publicKey,
      $styleParameter
     )
{
//create html string
 $recentComments = '<div id="dqRecentComments">';
 foreach($comment as $commentObj)
 {
  //get comment data
  $authorName = $commentObj["author"]["name"];
  $authorProfile = $commentObj["author"]["profileUrl"];
  $authorAvatar = $commentObj["author"]["avatar"]["permalink"];
  $message = $commentObj["message"];  
  $postTime = date(
       $styleParameter["dateFormat"] ,
       strtotime($commentObj["createdAt"])
      );
  $threadInfo = getThreadInfo(
          $commentObj["thread"],
          $publicKey
         );
  $threadTitle = $threadInfo["title"];
  $threadLink = $threadInfo["link"];
 
  // Fix gravatar images
  $authorAvatar = gravatarFix($authorAvatar);
  // shorten comment
  $message = shortenComment(
         $message,
         $styleParameter["commentLength"]
        );
  //create comment html
  $commentHtml = '<div class="dqCommentWrap">
       <div class="dqCommentHead">
        <div class="dqAvatarWrap">
         <img class="dqCommentAvatar" src="'
.$authorAvatar.'" alt="'.$authorName.'"/>
        </div>
        <div class="dqCommentMeta">
         <span class="dqCommentAuthor">
          <a class="dqProfileLink" href="'
.$authorProfile.'">'.$authorName.'</a>
         </span>
         <span class="dqCommentTime">'
.$postTime.'</span>
        </div>
        <div class="dqClear"></div>
       </div>
       <div class="dqCommentBody">
        <a class="dqCommentThread" href="'
.$threadLink.'">'.$threadTitle.'</a>
        <p class="dqCommentText">'
.$message.'</p>
       </div>
      </div>'
;
  $recentComments .= $commentHtml;
 }
 $recentComments .= '</div>';
 echo($recentComments);
}

function noComments()
{
 echo(
   '<div id="dqRecentComments">
   <span id="dqNoComments">No Recent Comments Found</span>
   </div>'

  );
 
}
function shortenComment($comment, $commentLength)
{
 if($commentLength != 0)
 {
  if(strlen($comment) > $commentLength)
   {
   $comment = preg_replace(
          '/\s+?(\S+)?$/', '',
          substr($comment, 0, $commentLength+1)
         )."...";
   }
 }
 return $comment;
}
function gravatarFix($img_url)
{
  $parsedImgLink = parse_url($img_url);
  parse_str($parsedImgLink["query"],$parsedQuery);
  if(stripos($parsedImgLink["host"], "gravatar") !== false)
  {
   return "http://www.gravatar.com/avatar/".$parsedQuery["gravatar_id"].".png";
  }
  else
  {
   return $img_url;
  }
}
function getThreadInfo(
       $threadId,
       $publicKey,
       $apiVersion = "3.0",
       $resource = "threads/details",
       $outputType = "json"
      )
{
$dqRequest ="http://disqus.com/api/".$apiVersion."/".$resource.".".$outputType;
$dqParameter = array(
      "api_key" => $publicKey,
      "thread" => $threadId
     );
$dqRequest = addQueryStr($dqRequest, $dqParameter);

// convert response to php object
$dqResponse= @file_get_contents($dqRequest);
if($dqResponse !== false)
{
 $dqResponse = json_decode($dqResponse, true);
 $dqThread = $dqResponse["response"];
 return $dqThread;
}
else
{
 $dqThread = array(
      title=> "Article not found",
      link => "#"
     );
 return $dqThread;
}
}
function addQueryStr($baseUrl,$parameters)
{
 $i=0;
 if (count($parameters) > 0)
 {
 $newUrl = $baseUrl;
  foreach($parameters as $key => $value)
  {
     if($i == 0)
     {
    $newUrl .="?".$key."=".$value;
   }
   else
   {
    $newUrl .="&".$key."=".$value;
   }
   $i +=1;
  }
 
  return $newUrl;
 }
 else
 {
  return $baseUrl;
 }
}
?>


Step 1: Add Your Parameters

  • commentLimit - Max amount of recent comments you want to fetch.
  • dateFormat - Format you want to use for comment post dates. Check php manual for formatting options.
  • commentLength - Max character count of comments
  • apiVersion - Version of Disqus api
  • resource - Disqus resource to grad data from. Probably want to leave this alone.
  • outputType - Format of response from Disqus. You'll have to change script if you want to use xml.
  • publicKey - Your public Disqus api key.
  • forumName - Forum name Disqus identifies your site by.

You'll notice that I split the parameters into two arrays. I think this makes the script more flexible. If you want to add an extra parameter to your Disqus request just add an extra key to the $dqparameter array.

Step 2: Create your request string, send to Disqus and grab the response

//Create base request string
  $dqRequest ="http://disqus.com/api/".$apiVersion."/".$resource.".".$outputType;
  //add parameters to request string
  $dqRequest = addQueryStr($dqRequest, $dqParameter);
  // get response with finished request url
  $dqResponse = @file_get_contents($dqRequest);
  //check repsonse
  if($dqResponse !== false )
  {
    // convert response to php object
    $dqResponse = json_decode($dqResponse, true);
    // get comment items from response
    $dqComment = $dqResponse["response"];

All disqus request require an apiversion, resouse, and output type. That's done in the first line above. The second line of code above calls my custom function addQueryStr. It simply takes a base url and array then returns the full url with a query string. The next step is to use the file_get_contents function with the completed request string to get a response. Note the  @ in front of file_get_contents. That will suppress a php warning from being displayed if your request fails. Since json was used as the output type when making the request json_decode is called to decode the response. The 2nd parameter in the json_decode function turns objects into associative arrays. The last part of this step was saving the comment objects from the response in the variable  $dqComment.

function addQueryStr($baseUrl,$parameters)
{
  $i=0;
  if (count($parameters) > 0)
  {
  $newUrl = $baseUrl;
    foreach($parameters as $key => $value)
    {
       if($i == 0)
       {
        $newUrl .="?".$key."=".$value;
      }
      else
      {
        $newUrl .="&".$key."=".$value;
      }
      $i +=1;
    }
   
    return $newUrl;
  }
  else
  {
    return $baseUrl;
  }
}


Step 3: Grab Comment Data, Create a String of HTML,  Echo HTML String

This is pretty much the last important step. After checking if any comments were returned in the response I then call my custom function echoComments. This function loops over each comment item, grabs the relevant information, and then creates an html string for display. After each iteration the $commenthtml string is added to the $recentComments variable. Almost every element in $commentHtml was given a css class so that I could easily change how my recent comments list looks without changing the script. I have not included my css in this article, but this is the same script that I use on this blog. You could just use firebug to see what I am doing with css.

function echoComments(
      $comment,
      $publicKey,
      $styleParameter
     )
{
//create html string
 $recentComments = '<div id="dqRecentComments">';
 foreach($comment as $commentObj)
 {
  //get comment data
  $authorName = $commentObj["author"]["name"];
  $authorProfile = $commentObj["author"]["profileUrl"];
  $authorAvatar = $commentObj["author"]["avatar"]["permalink"];
  $message = $commentObj["message"];  
  $postTime = date(
       $styleParameter["dateFormat"] ,
       strtotime($commentObj["createdAt"])
      );
  $threadInfo = getThreadInfo(
          $commentObj["thread"],
          $publicKey
         );
  $threadTitle = $threadInfo["title"];
  $threadLink = $threadInfo["link"];
 
  // Fix gravatar images
  $authorAvatar = gravatarFix($authorAvatar);
  // shorten comment
  $message = shortenComment(
         $message,
         $styleParameter["commentLength"]
        );
  //create comment html
  $commentHtml = '<div class="dqCommentWrap">
       <div class="dqCommentHead">
        <div class="dqAvatarWrap">
         <img class="dqCommentAvatar" src="'
.$authorAvatar.'" alt="'.$authorName.'"/>
        </div>
        <div class="dqCommentMeta">
         <span class="dqCommentAuthor">
          <a class="dqProfileLink" href="'
.$authorProfile.'">'.$authorName.'</a>
         </span>
         <span class="dqCommentTime">'
.$postTime.'</span>
        </div>
        <div class="dqClear"></div>
       </div>
       <div class="dqCommentBody">
        <a class="dqCommentThread" href="'
.$threadLink.'">'.$threadTitle.'</a>
        <p class="dqCommentText">'
.$message.'</p>
       </div>
      </div>'
;
  $recentComments .= $commentHtml;
 }
 $recentComments .= '</div>';
 echo($recentComments);
}

One important thing to note about the echoComments function is that comment objects do not contain the title of the article that the comment was posted on. Instead each comment object contains the ID number of the thread (blog,article post,etc). Thus another call needs to be made the to the disqus api for the thread title. I use my getThreadInfo function below for exaclty that.

function getThreadInfo(
       $threadId,
       $publicKey,
       $apiVersion = "3.0",
       $resource = "threads/details",
       $outputType = "json"
      )
{
$dqRequest ="http://disqus.com/api/".$apiVersion."/".$resource.".".$outputType;
$dqParameter = array(
      "api_key" => $publicKey,
      "thread" => $threadId
     );
$dqRequest = addQueryStr($dqRequest, $dqParameter);

// convert response to php object
$dqResponse= @file_get_contents($dqRequest);
if($dqResponse !== false)
{
 $dqResponse = json_decode($dqResponse, true);
 $dqThread = $dqResponse["response"];
 return $dqThread;
}
else
{
 $dqThread = array(
      title=> "Article not found",
      link => "#"
     );
 return $dqThread;
}
}


Other, Less Important Parts of Code:
I noticed gravatar images where coming in very small, which made images look pixelated due to my css settings. Thus, I wrote the function below to grab the version of the user's gravatar image that has not been resized. So far it has worked for me, but I have not tested it extensively so let me know if you have any problems with it.
 

function gravatarFix($img_url)
{
  $parsedImgLink = parse_url($img_url);
  parse_str($parsedImgLink["query"],$parsedQuery);
  if(stripos($parsedImgLink["host"], "gravatar") !== false)
  {
   return "http://www.gravatar.com/avatar/".$parsedQuery["gravatar_id"].".png";
  }
  else
  {
   return $img_url;
  }
}

I use a function called noComments in my script for situations where no comments are returned or when I encounter an error.

function noComments()
{
 echo(
   '<div id="dqRecentComments">
   <span id="dqNoComments">No Recent Comments Found</span>
   </div>'

  );
 
}

Hopefully this helps a few people get a recent comment module up quickly on their site. If you use it please let me know how it works out for you.


blog comments powered by Disqus