If you’ve included any social buttons on your site, such as the Facebook like button, you can usually see how many people have clicked on it. It’s all done through JavaScript but you can also retrieve that number using PHP. Facebook has the Graph API and Twitter offers a similar API.
Let’s do a quick test to see how each API works in regards to gathering your page statistics.
http://graph.facebook.com/http://bavotasan.com/2011/style-select-box-using-only-css/
The above returns:
{ "id": "http://bavotasan.com/2011/style-select-box-using-only-css/", "shares": 69 }
If you are using Facebook comments, you will also see a comments variable in the returned JSON code.
Twitter is quite similar:
http://urls.api.twitter.com/1/urls/count.json?url=http://bavotasan.com/2011/style-select-box-using-only-css/
That will return:
{ "count":47, "url":"http:\/\/bavotasan.com\/2011\/style-select-box-using-only-css\/" }
Here’s a small function you can add into your WordPress functions.php file so that your page stats are gathered and stored.
add_action( 'wp', 'bavotasan_gather_post_stats' ); /** * Gather and store post stats * * @uses wp_remote_fopen() To fetch remote URL * * @author c.bavota */ function bavotasan_gather_post_stats() { if ( is_single() ) { $post_id = get_the_ID(); $transientkey = 'post_stats_' . (int) $post_id; if ( false === get_transient( $transientkey ) ) { $post_url = get_permalink(); $stat = array(); $twitter_url = 'http://urls.api.twitter.com/1/urls/count.json?url=' . $post_url; $twitter_stat = json_decode( wp_remote_fopen( $twitter_url ) ); $stat['twitter'] = empty( $twitter_stat->count ) ? '0' : (int) $twitter_stat->count; update_post_meta( $post_id, '_twitter_count', $stat['twitter']); $facebook_url = 'http://graph.facebook.com/' . $post_url; $facebook_stat = json_decode( wp_remote_fopen( $facebook_url ) ); $stat['facebook'] = empty( $facebook_stat->shares ) ? '0' : (int) $facebook_stat->shares; update_post_meta( $post_id, '_facebook_shares', $stat['facebook']); set_transient( $transientkey, $stat, 60 * 60 * 1 ); // one hour } } }
When someone visits your page, the function will run and store a transient containing your page stats. The transient will be refreshed every hour, as long as someone revisits your page. It will also create two custom fields that contain your Twitter count and Facebook shares. With those two values stored, you can easily create a list of your top posts according to the number of shares or Tweets.