I am a bit of an amateur when it comes to PHP and WordPress but I have rigged up the following code:

function fb_comment_count($url="some url here") {
$filecontent = file_get_contents('https://graph.facebook.com/?ids=" . $url);
$json = json_decode($filecontent);
$count = $json->$url->comments;
if ($count == 0 || !isset($count)) {
    $count = 0;
}
echo $count;
}

What it does is it retrieves the comment count from the Facebook Graph and displays it on a page. For it to work, I have to manually declare the url for each call.

What I”m having a hard time with, is setting it up so that when you call the function in the template, it defaults to the post’s permalink. I honestly have tried everything that has come to my mind.

get_permalink() doesn’t work when you declare the arguments in the function.

Any help would be GREATLY appreciated.
Thanks!

3 Answers
3

Final version of code used:

    function fb_comment_count($link = 'link') {
global $post;
$url="https://graph.facebook.com/";
$posturl = get_permalink($post->ID);
$url .= $posturl;

$filecontent = wp_remote_retrieve_body(wp_remote_get($url, array('sslverify'=>false)));
$json = json_decode($filecontent);
$count = $json->comments;
if ($count == 0 || !isset($count)) {
    $count = 0;
}

$comments = $count;
if ($count == 1) {
    $comments .= ' Comment';
}
elseif ($count == 0) {
    $comments="Leave a Comment";
}
elseif ($count > 1) {
    $comments .= ' Comments';
}
if ($link == 'nolink') {
    echo $comments;
}
else {
    echo '<a href="'.$posturl.'#comments" title="Comments for '.$post->post_title.'">'.$comments.'</a>';
}
}

Leave a Reply

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