Facebook Comment Count

时间:2011-05-29 作者:Zack Austin

谈到PHP和WordPress,我有点业余,但我编造了以下代码:

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;
}
它所做的是从Facebook图表中检索评论计数,并将其显示在页面上。为了让它工作,我必须手动声明每个调用的url。

我很难理解的是,如何设置它,以便在模板中调用函数时,它默认为帖子的永久链接。老实说,我已经尝试了我想到的一切。

在函数中声明参数时,get\\u permalink()不起作用。

任何帮助都将不胜感激。谢谢

3 个回复
SO网友:Zack Austin

所用代码的最终版本:

    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>\';
}
}

SO网友:VicePrez

试试这个,看看它给你带来了什么:

function 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 = 0;
}
echo $count;
}

SO网友:skarz

如果您可以使用此选项,则看起来非常复杂:

<fb:comments-count href="<?php echo get_permalink($post->ID); ?>"></fb:comments-count> Comments

结束