I would like to have a list of my most liked posts from facebook, and place it in the sidebar. Is there a way for doing it? (and if so, how?)
2 Answers
A quick google brought up these, which led me to this post.
You can access the site’s object in the Graph and get the current “Fan
count”. i.e.
http://graph.facebook.com/http://google.com.
Note that you will need an oauth tokenThis is definitely the
to do this.
most accurate way of getting a page’s
Likes.You can also use the javascript SDK to detect when a user clicks the Like
button and then make an ajax call in
the background to a php page that adds
to a counter or does whatever you want
it to. You can also detect when a user
Unlikes a page too.
In other words, 1) queries Facebook for the number of likes, 2) suggests to hook into the ‘liking’ action, counting & logging the ‘likes’ on your site.
Either way you’re going to need to get stuck in to the Facebook API. If you go for 1), you’ll also need the PHP SDK.
I’d say 1) would be the better of the two, since it’s non-JavaScript dependent, and getting ‘likes’ from other sources won’t affect it (i.e. people liking your page using means other than the button on your site).
Since it looks like you can only query one page (URL) at a time (unless a Facebook guru can correct me?), you’d need some way of frequently caching the like counts of all your posts.
Perhaps a wp_cron
function that continually loops over say, 20 posts, every hour (check Facebook usage terms), and updates the like count as a post meta entry.
To get the ‘most liked’ posts, you could then simply query posts that have the meta key, and order by the meta value.
new WP_Query( array( 'meta_key' => 'like_count', 'orderby' => 'meta_value_num', 'posts_per_page' => 5 ) );