Getting Facebook Comment Count Within WordPress

By mike on December 29, 2011 in Snippet
w0
k 0

I’ve been working with the Facebook Comment integration into WordPress lately. Mostly because it can help cut down on spam, but also because of the grammer checker and social media benefit. I couldn’t really find a good solution online for pulling the number of comments on any given post, so here is what I ended up with. I included this in my functions.php file, and just put this: <?php get_fb_comment_count(); ?> in my single.php file where I want the comment number to be displayed.

function get_fb_comment_count() {
     global $post;
     $url = get_permalink($post->ID);
     $filecontent = file_get_contents('https://graph.facebook.com/?ids=' . $url);
     $json = json_decode($filecontent);
     $count = $json->$url->comments;
     if ($count == 0 || !isset($count)) {
          $count = 'No Comments';
     } elseif ( $count == 1 ) {
          $count = '1 Comment';
     } else {
          $count .= ' Comments';
     }
     echo $count;
}

0 Comments

Leave a reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>