Add custom Facebook share link with share count and variable text

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

news site homepage

Read More

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?

Related posts

1 comment

  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); ?>
    

Comments are closed.