Count the Number of Shares to Facebook, Twitter, LinkedIn & Google Plus

I’ve recently consolidated two websites (FlyingTraining.net and CrewResourceManagement.com) into flight.org as a means of managing my time and resources more effectively. The other sites will be revived in one way or another but they’ll be built ‘low maintenance’. Apart from the multiple site to manage, there was a large overlap in content that was far too difficult to ignore.

In the process of moving posts across I couldn’t work out an effective manner in which to retain Facebook shares, Twitter counts and so on. Instead of implementing a solution that would have been rather server intensive, I decided to simply retrieve the post count from a few networks and display that information under each post.

This post details how to retrieve post counts from the big four social networks and – if you’re interested enough - how to render that data on your screen in a small text box. I’ve posted about Twitter counts before in isolation; this post expands upon the same theme.

The Naked Functions

Get Number of Tweets from Twitter

function get_tweets($url) {     
  $json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);
  $json = json_decode($json_string, true);
  return intval( $json['count'] );
}

Get Number of LinkedIn Shares

function get_shares($url) {     
  $json_string = file_get_contents("http://www.linkedin.com/countserv/count/share?url=$url&format=json");
  $json = json_decode($json_string, true);
  return intval( $json['count'] );
}

Get Number of Facebook Shares

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'] );
} 

Get Number of Google+1′s

function get_plusones($url) {
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
  $curl_results = curl_exec ($curl);
  curl_close ($curl);
  $json = json_decode($curl_results, true);
  return intval( $json[0]['result']['metadata']['globalCounts']['count'] );
}

To display the data, simply use:

echo get_tweets("http://www.flight.org/blog/2012/04/22/gear-up-landings-and-pilot-error/");

The above will return “22” (at the time of writing).

Getting ALL the data at the same time

I wanted to get all the data into a textbox for inclusion into each post I wanted to migrate. The following dodgy function will obtain all the necessary data from Twitter, LinkedIn, Facebook and Google Plus.

Including Social Data on a WordPress Post or Page with Shortcode

The above function does what I’m after, but the only efficient way of having it display within a post was by way of shortcode. Because I didn’t want to repeatedly make requests to the API’s of the big-four, I cache the results locally. You’re required to add the following block of code into your theme’s functions.php file or add it into your shortcode plugin.

function getShares($atts) {
  extract(shortcode_atts(array(
    'url' => '',
    'bordercolor' => '#dddddd',
    'textcolor' => '#333333',
    'border ' => '1',
    'bordertype' => 'solid',
    'bgcolor' => '#f7f7f7',
  ), $atts));
 $urlsnip = substr("$url", 0, 30);
 $sharestransient = 'socialshares_' . $urlsnip;
 $cachedresult =  get_transient($sharestransient);
 if ($cachedresult !== false ) {
	return $cachedresult;
	} else {
  $json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $url);
  $json = json_decode($json_string, true);
  $twitter = intval( $json['count'] );

  $json_string = file_get_contents("http://www.linkedin.com/countserv/count/share?url=$url&format=json");
  $json = json_decode($json_string, true);
  $linkedin = intval( $json['count'] );

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

  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
  $curl_results = curl_exec ($curl);
  curl_close ($curl);
  $json = json_decode($curl_results, true);
  $plusone = intval( $json[0]['result']['metadata']['globalCounts']['count'] );

  if ($twitter != "0") $text .= "<strong>Twitter</strong>: $twitter times ";
  if ($linkedin != "0") $text .= "<strong>LinkedIn</strong>: $linkedin times ";
  if ($facebook != "0") $text .= "<strong>Facebook</strong>: $facebook times ";
  if ($plusone != "0") $text .= "<strong>GooglePlus</strong>: $plusone +1's";

  $result = "<br><p style=\"padding: 4px 4px 4px 4px; color: $textcolor; border: $bordercolor $border $bordertype; background: $bgcolor\">This page was shared on the following social networks - $text</p><br>";

  set_transient($sharestransient, $result, 60*60*4);
  update_option($sharestransient, $result);
  return $result;
  }
}
add_shortcode('postshare', 'getShares');

I’ll retrieve data for the post at http://www.flight.org/blog/2012/04/22/gear-up-landings-and-pilot-error/ using the following code:

[postshare url=”http://www.flight.org/blog/2012/04/22/gear-up-landings-and-pilot-error/”]

The shortcode will render the following block of data on your page:


This page was shared on the following social networks - Twitter: 155 times LinkedIn: 3 times Facebook: 19 times GooglePlus: 1 +1's


If you so choose, you can change the look and feel of the text box using the shortcode parameters of textcolor, border, bordercolor, bordertype or bgcolor. The URL is the only parameter that must be defined.

First Name:
Your Email Address:
 




Download: Social Shares PHP and WordPress shortcode
Description: Get social shares from various networks. PHP and WordPress code.
Author:Marty
Category: PHP code
Date: May 4, 2012



If you liked this article, you may also like:

  1. Determine the Relationship between two Twitter Users
  2. Twitter using CURL via their API
  3. Include Twitter Data on your Website
  4. Why You Should NEVER Post Your Email to Twitter
  5. Count the number of times your page is Tweeted via the TweetMeme API
About Marty

is a passionate web developer from Sydney, Australia. He owns about 600 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. Follow Marty on Twitter or Google+.

Comments

  1. Neo says:

    Thanks!

  2. Ryan says:

    This is a great article! thank you! Just wondering how i would go about using the shortcode to pull in the count per post that is shared. I am using the short code like so in the loop for posts:

    but I am not getting anything back.

  3. Jason says:

    Hi!

    Thanks for the great article! I’m using it on my WP website.

    But by the Google+ counts I’m getting this error:
    Fatal error: Call to undefined function curl_init()

    I’m using WP 3.4.

    Can you please help?

    Thanks

  4. Matt says:

    Is there a way to add all the shares? So instead of having each separate, it would list the total? Something like how Mashable does it, I think.

    • Marty says:

      Sure. What I’ve provided above is grossly inefficient… to the point of negligence. I’ve got a database that stores the results of shares etc every few hours. Using my method it’s simply an issue of retrieving the shares attached to each post ID. I’ll try and find the time to post something soon.

      Using the above dodgy method, you can simply use addition to tally the total results. It’ll work, but it’s not best practice.

      It might be best if I email you an example.

  5. Nick says:

    Amazing post. Thank you so much!

  6. Daniel says:

    Thanks for your post.
    And now I found that… facebook functions should be changed for proper working like below.

    function get_likes($url) {
    $json_string = file_get_contents(‘http://api.ak.facebook.com/restserver.php?v=1.0&method=links.getStats&format=json&urls=’ . rawurlencode($url));
    $json = json_decode($json_string, true);
    return intval( $json[0]['like_count'] );
    }

  7. deb says:

    can you mail me an example file !!! i really liked your good work :)

  8. Hasan Zaheer says:

    very good article, was looking for these codes since long. now I am going to use that social couter ;)

    cheers.

Speak Your Mind

*