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.
|
|
Download: Social Shares PHP and WordPress shortcode |
If you liked this article, you may also like:


Thanks!
Really helpful article. Here is a complete list of code snippets to fetch social counts from various sites like facebook, twitter, google plus, pinterest etc: http://cube3x.com/get-social-share-counts-a-complete-guide/
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.
didn’t seem to like my code. Here’s a pastebin link…
http://pastebin.com/P6StCm9d
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
Hi. Is CURL enabled on your server? Seems like it isn’t.
I’ve fixed this at the moment, by activating curl on my server.
But by the Facebook likes, I’m getting this error:
Undefined index: shares in functions.php on line 464
Will get back to you. Have to look at the code.
Did you already have the time to take a look at the code to fix it?
Thanks.
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.
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.
Do you mind emailing me an example? I would definitely like to get this to work.
Sure. I’ll write up an example in a couple of days.
I’m also interested. For some reason, the count of Facebook shares doesn’t seem to work anymore. It doesn’t add up to the total.
Could you email me that example too? Also, what do you think of http://sharedcount.com/ ? Which of these two would be the best solution?
Hi there, I would also like to implement this on my website. Could you send me the write-up (if you happened to get around to it)?Would be much appreciated. Thanks.
Amazing post. Thank you so much!
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'] );
}
can you mail me an example file !!! i really liked your good work :)
very good article, was looking for these codes since long. now I am going to use that social couter ;)
cheers.