Top 3 posts in last week ordered by Facebook and Twitter share counts

I am interested in displaying the top 3 stories in the past week based on the total number of shares on Facebook and Twitter. I have found that these share counts are more useful indications of what is popular in comparison to sorting by the number of comments using 'orderby' => 'comment_count'.

So my question is: What is the best way to sort posts based on the number of Facebook or Twitter shares? I’m a little concerned about the number of requests to the Facebook and Twitter APIs if I were to check the number of shares for all of the posts in the past week, and then go from there. Thanks in advance!

Related posts

Leave a Reply

2 comments

  1. This is a bit of a multi-part question, so you’re getting a multi-part answer.

    • Getting the Facebook count can be done by making a request to https://graph.facebook.com/URL. This will return a json object which contains, among other things, the number of “shares”.

    Working example which has 4 shares as of this writing: https://graph.facebook.com/http://ottopress.com/2011/wp-quickie-adding-chrome-voice-search/

    One thing I didn’t document there was that if you leave the callback parameter blank, you get back a json object without the JSONP callback stuff.

    Working example which has 29 twitter count as of this writing: http://urls.api.twitter.com/1/urls/count.json?callback=&url=http://ottopress.com/2011/wp-quickie-adding-chrome-voice-search/

    • Now that you have those URLs, you need to write some functions to periodically get them for each of your posts (presumably in the last week) and to then store that data in a postmeta field. You can use a wp-cron job or transients for their expiration times. Either way.

    Once you have the data, and have stored it in a postmeta for each post in question, then selecting based on it is a matter of using the meta_key in the post query, along with an orderby=meta_value_num parameter. This will allow you to select posts and order them by the value you’re storing in the postmeta.

  2. Do you mean calendar week or rolling week (previous seven days) ? How many posts are we talking about?

    I’d try something like this:

    1. Create wp-cron task.
    2. In cron select posts that qualify for timeframe display and have missing/outdated stats.
    3. Query APIs and save stats and time of check (to check if stats are outdated in previous step) in custom meta fields.
    4. On front end query for wanted and sort by stats custom field.

    This is just one of many ways to do it, it depends a lot on how likely you are to stress out API – the faster you are running out of available requests the more logic and caching you need to consider and implement.