PHPology is a collective of highly skilled, award winning, web gurus.
Contact Raj on 07985 467 213 or email [email protected]

Customize Disqus CSS

During the Xmas period, a Word Press blog I was working on required the use of Disqus widgets.

Altho the out of the box layout has everything you need, the design I had to tackle with was not so easy. Various elements had to be placed in a certain way and had to support alternative colour rows.

Using the CSS override option did not do that much of a great job as pin pointing various html elements was a pain in the arse, which then I thought, can I not use PHP to do some magic with it?

The answer took a while to find but the below code, altho I still think is a very bad short cut worked a treat.

The idea was, read in the output from the Disqus js file using fopen and then using a HTML Dom module, find the html elements you wanted to use. I had to do some dodgy substr and str_replace action but the output was ideal for any CSS developer to customize.

The code below is for commenters but its the same idea for recent comments and popular threads.

<?php
     require('simple_html_dom.php'); //get it from here http://simplehtmldom.sourceforge.net/manual.htm

     $file = "http://disqus.com/forums/USERNAME/top_commenters_widget.js?num_items=5&hide_mods=0&hide_avatars=0&avatar_size=24";
     $str = null;
     $handle  = fopen($file, "r");
     while (!feof($handle)) {
       $str .= fread($handle, 8192);
     }
     fclose($handle);
     $str = stripslashes($str);
     $strpos = strpos($str, "<ul class=");
     $str = substr($str, $strpos);
     $str = str_replace("');", "", $str);
     $str = str_replace("&nbsp;&middot;&nbsp;", "-", $str);
     //echo $str;

     // get DOM from URL or file
     $html = str_get_html($str);
     //print_r($html);

     $i = 0;
     foreach($html->find('li') as $e)
     {
      $avatar = $e->children(0);
      $user = $e->children(1);
      $meta = $e->children(2)->plaintext;
      list($clout, $posts) = explode("-", $meta);

      $alternative = (fmod($i, 2) == 0) ? "even" : "odd";

      echo "<div class="top-commenters ".$alternative."">";
      echo $avatar . " ";
      echo $user . "<span>";
      echo $posts . "</span><span>";
      echo $clout . "</span>";
      echo "<div style="clear: both;"></div>";
      echo "</div>";

      $i++;
     }
?>