问题
I would like my subtitles in my Wordpress blog to count the number of Facebook comments on my post. After inserting Facebook's code
<span class="comment-count">
<fb:comments-count href="<?php echo get_permalink($post->ID); ?>">
</fb:comments-count> comments
</span>
I realise that when I only have 1 comment it prints "1 comments", in plural. What changes in the code do I need to do in order to:
- print "No comments" when no comments
- print "1 comment" in singular, when only one comment
- print "X comments" in plural, when more than one comment
Sorry if this is a dumb question but I am completely new to coding (PHP), Wordpress and the Facebook tools.
回答1:
Using the fb:comments-count
tag by itself, you can't. What you need to do is get the number of comments into a PHP variable first and then print the correct phrase depending on the value of that variable. You can retrieve the number of comments using the PHP SDK, FQL, or the Graph API. Then, one way to print what you want:
<?php
$comments = getCommentCountUsingGraphAPI();
if ($comments == 0) {
echo "No comments";
} elseif ($comments == 1) {
echo "1 comment";
} else {
echo "$comments comments";
}
?>
But it's a lot easier to compromise and just modify your presentation a little to avoid the pluralization issue entirely:
<span class="comment-count">
Comments: <fb:comments-count href="<?php echo get_permalink($post->ID); ?>"></fb:comments-count>
</span>
Or:
<span class="comment-count" title="Comments">
<fb:comments-count href="<?php echo get_permalink($post->ID); ?>"></fb:comments-count>
</span>
回答2:
An alternative to the straight PHP method would be using the ngettext() function.
<?php
echo ngettext("%d comment", "%d comments", $comments);
?>
回答3:
I combined John's solution with 9bugs tip with FQL and it works great. Add this to functions.php:
function fbCount($url) {
$base_url = "http://graph.facebook.com/fql?q=";
$query = "SELECT like_count, total_count, share_count, click_count, comment_count FROM link_stat WHERE url = '$url' ";
$new_url = $base_url . urlencode($query);
$data = @file_get_contents($new_url);
$data = json_decode($data);
return $data->data[0];
}
Then add this to where you want the comment count to show in content.php:
$url = get_permalink($post->ID);
$fb = fbCount($url);
if ($fb->comment_count == 0) {
echo '<a href="' . $url . '"> leave a comment! </a> ';
} elseif ($fb->comment_count == 1) {
echo '<a href="' . $url . '"> 1 </a> comment';
} else {
echo '<a href="' . $url . '"> '. $fb->comment_count . '</a> comments';
}
来源:https://stackoverflow.com/questions/8286964/how-do-i-change-the-singular-plural-on-comment-to-comments-on-facebooks-num