1

I'm trying to do this in a news site homepage.

news site homepage

The part I'm struggling with is the Facebook share link text. It should:

  • count the share/link of the specific post
  • hide the number is it's 0
  • write "share!" if it has 0 share
  • write "shared 1 time" if it has 1 share
  • write "n shares" if it has more than 1 shares.

The text is arbitrary, I would like to be able to control it.

I found this code to get the likes count:

function get_likes($url) {
 $json_string = file_get_contents('http://graph.facebook.com/?ids=' . $url);
 $json = json_decode($json_string, true);
 return intval( $json[$url]['shares'] );
} 

And I managed to use it to get the actual share count:

<a href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&t=<?php the_title(); ?>">
 <?php $url = get_permalink( $post_id ); echo get_likes("$url"); ?> shares</a>

Now the difficult part would be how to control the text the same way it's controlled in "comments_number":

comments_number( 'no responses', 'one response', '% responses' );

Any hint?

4
  • This is almost the same question: wordpress.stackexchange.com/questions/47220/…
    – kraftner
    Commented Feb 20, 2014 at 12:26
  • Uhm, I could be wrong but it seems that question address how to count Wordpress stored values and not external one, isn't it? I imagine the solution would involve some sort of calculation in the get_likes($url) function.
    – molokom
    Commented Feb 20, 2014 at 15:01
  • get_likes only returns a number. So returning the appropriate text is all that is missing and that is covered in the answer I linked to. Unless I got something wrong...
    – kraftner
    Commented Feb 20, 2014 at 15:03
  • I found a different answer that did the trick! stackoverflow.com/questions/8286964/…
    – molokom
    Commented Feb 20, 2014 at 15:39

1 Answer 1

1

I found a simple solution thanks to this answer: How do I change the singular/plural on “comment” to “comments” on Facebook's number of comments?

Here is how I solved without the tag, using the code I was already working for, this goes into function.php

function get_likes($url) {
   $json_string = file_get_contents('http://graph.facebook.com/?ids=' . $url);
   $json = json_decode($json_string, true);
   $count = intval( $json[$url]['shares'] );
   if ($count == 0) {
     echo "share!";
   } elseif ($count == 1) {
     echo "shared 1 time";
   } else {
   echo "$count shares";
   }
} 

and this in the template

<?php $url = get_permalink( $post_id ); echo get_likes($url); ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.