How to make (sort) gallery/post votings (likes) with Facebook
I will tell you have to make sorting of photos/posts/links via facebook.
For example you have photo gallery where users could “vote” (like) for each photo. And you need to make sorting of photos by popularity with Facebook.
So you have, for example, 10 photos with urls:
http://yoursite.com/photo/1,
http://yoursite.com/photo/2,
..,
http://yoursite.com/photo/10
what users could “like”. And you have pagination of 3 photos per page. So lets start.
First you need connect to facebook using Facebook PHP SDK
1
2
3
4
5 $facebook = new Facebook(array(
'appId' => APPLICATION_ID,
'secret' => APPLICATION_SECRET_KEY,
'cookie' => true, // enable optional cookie support
));
then we need these variables
1
2
3
4
5
6
7
8
9
10
11 //current page
$page = isset($_GET['p'])?$_GET['p']:1;
$page = (int)$page;
//count of photos, of course you should use own query
$q = mysql_query("SELECT COUNT(id) as photos_count FROM photos");
$res = mysql_fetch_assoc($q);
$photos_count = $res['photos_count']; // we have 10
// Total pages, so we will have 4 total pages
$pages_count = ceil($photos_count/NUMBER_PHOTOS_PER_PAGE);
// For pagination
$from_photo = ($page-1)*NUMBER_PHOTOS_PER_PAGE;
And we need array of our links, what users could like (you should change to own url)
1
2
3
4
5 $links = array();
$q = mysql_query('SELECT CONCAT("\"http://yoursite.com/photo/",id,"\"") as link from photos');
while ($row = mysql_fetch_assoc($q)) {
array_push($links,$row['link']);
}
Now lets get photos ordered by “like” from facebook
1
2
3
4
5
6
7
8
9
10
11 $links = join(",",$links);
$res = $facebook->api(array(
'method' => 'fql.query',
'query' => 'SELECT url FROM link_stat WHERE url IN ('.$links.') ORDER BY total_count DESC LIMIT '.$from_photo.','.NUMBER_PHOTOS_PER_PAGE));
$ids = array(); // ids of photos to show
// parse urls to get ids. (You should replace regexp, or maybe own method to fetch id from url)
foreach($res as $link_stat) {
preg_match('/[0-9]+$/', $link_stat['url'],$matches);
$id = $matches[0];
array_push($ids, $id);
}
So now we need just output this photos from DB sorting like array
1
2
3
4
5
6
7 $ids = join(',',$ids);
$q = mysql_query('SELECT * from photos WHERE id IN ('.$ids.')
ORDER BY FIELD(id,'.$ids.')');
while ($photo = mysql_fetch_assoc($q)) {
.....
// output or do something else with photos
}
And of course you should add “like” button to each photo
1 <fb:like href="http://yoursite.com/photo/<?php echo $photo['id']?>" show_faces="false" layout="button_count" width="158"></fb:like>
and pagination, with ?p parameter
If you have some problems or question, just post a comment
