twitter

Recent Comments

parallels promo code
parallels promo code May 20, 2012 at 9:58PM
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

Aaron J. White
Aaron J. White May 11, 2012 at 1:16PM
Using KeePass with Internet Explorer
The file name has to end in .js. So the filename should be URL-In-Title.user.jsMake sure that...
HsN
HsN May 11, 2012 at 11:26AM
Using KeePass with Internet Explorer

By the way, Iam using IE - 9.0.5 and KeePass - 2.19 for at this moment.

HsN
HsN May 11, 2012 at 11:18AM
Using KeePass with Internet Explorer
I followed each step but I am not seing Trixies Options (point 5), even though I restarted my...
Aaron J. White
Aaron J. White May 1, 2012 at 8:00PM
Damien van Holten
Damien van Holten May 1, 2012 at 7:27AM
Creating A Recent Comments Widget With Disqus's API and PHP

Looking at that username, link and generic comment I would say it's a bot.

Aaron J. White
Aaron J. White April 10, 2012 at 6:15AM
Using KeePass with Internet Explorer
Well, I can't recommend anything without a bit more detail. What version of IE are you using?...
Terugbelfunctie
Terugbelfunctie April 10, 2012 at 5:58AM
Using KeePass with Internet Explorer

it did not work for me, done everything as described ??

Aaron J. White
Aaron J. White March 14, 2012 at 10:00AM
Creating A Recent Comments Widget With Disqus's API and PHP

Decision for what? If you don't mind me asking.

USB 3G
USB 3G March 14, 2012 at 2:56AM
Creating A Recent Comments Widget With Disqus's API and PHP
I am really glad I read this article! With this it has really helped me with my...
Aaron J. White
Aaron J. White March 1, 2012 at 1:12PM
Using jQuery and Google Finance to Create a Simple Stock Ticker
Hi akhil. Thanks for your comment. There are a few things wrong with your code though. 1. You...
akhil
akhil February 29, 2012 at 12:31PM
Using jQuery and Google Finance to Create a Simple Stock Ticker
Thanks Aaron for the script. However, the script needs some tweaks for refreshing the price...
David Boyer
David Boyer January 13, 2012 at 4: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 3: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

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. There is a download link at the bottom of this post with all the code as a text file. 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';
  //$hourOffset = -6;
  $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,
    //"offset" => $hourOffset*60*60,
    "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();
  echo($e);
}

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"].'+0000') /*+ $styleParameter["offset"]*/
            );
    $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>
                <div class="dqCommentText">'
.$message.'</div>
              </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("/<.*?>/", "", $comment);
      $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"].'+0000') /*+ $styleParameter["offset"]*/
      );
  $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>
        <div class="dqCommentText">'
.$message.'</div>
       </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.

Update [3/1/2012] : My script was giving the wrong post time values. This is because Disqus does not add the timezone information in the "createdAt" attribute. Without something identifying the current timezone php's strtotime function will not do the proper conversion to the server's default timezone. Since Disqus returns GMT the fix is to add +0000 to the time string.
So strtotime($commentObj["createdAt"]) changes to strtotime($commentObj["createdAt"]."+0000") .
I have already made the change to the code above.

Update [3/30/2012]: I noticed there was extra spacing in the comments coming from this script. This is because Discuss returns the comments as html and not only text. To fix this I added one line to the
shortenComment function in the script. 
$comment = preg_replace("/<.*?>/", "", $comment)I have updated the code in the script.

Attachments:
Download this file (disqusRecentComments.php.txt)disqusRecentComments.php.txt[ ]5 Kb

blog comments powered by Disqus