I’m working on a project that will end up being age-gated because of graphic content. (No, not porn, unfortunately, but a blood and gore video game is almost as good.) It’s also like-gated, so we needed to fetch the number of people who liked the page, so that certain content would be unlocked when the like-count reached a certain number.
On a non-age-gated page, this is pretty simple using the Open Graph. Take the open graph page for vitaminwater, for example:
"website": "[removed for brevity]",
"mission": "[removed for brevity]",
"products": "[removed for brevity]"
As you can see, the number of likes (as well as some other information) is right there in the JSON response.
On an age-gated page, however, accessing the open graph gives simply:
For example: https://graph.facebook.com/battlefield
Because the page is age-gated, that open graph data isn’t available without an authentication token (so that Facebook knows who you are and that you’re old enough to view that content). Of course, since this is just going to be a tab, we didn’t want to force users to have to allow or authenticate with the app, so that sucked.
We contemplated running some cron jobs to fetch and cache the number of likes using fake users to authenticate against. And then we realized that we’re idiots.
Using the simple Open Graph call to determine the number of likes and shares on any object, we were able to get the number of likes without having to force anyone to authenticate.
Unfortunately, as Jangla pointed out in the comments, that actually returns a hybrid number that Facebook uses that consists of likes, shares and comments. It’s fine for a general number most of the time, but if you’re building something that is dependent on the actual number of likes in order to unlock something, a “sort of close” number just won’t cut it.
Enter a simple FQL query. The page ID for Snipe.Net’s Facebook page is 116633947708:
require_once 'facebook-php-sdk/src/facebook.php'; // Create our Application instance. $facebook = new Facebook(array( 'appId' => 'YOUR APP ID', 'secret' => 'YOUR SECRET KEY', 'cookie' => true, )); $result = $facebook->api(array( 'method' => 'fql.query', 'query' => 'select fan_count from page where page_id = 116633947708;' )); echo $fb_fans = '<li>'.$result['fan_count'].' likes for snipe.net';
The page ID for Battlefield (which is age-gated, remember) is 308775617671:
$result = $facebook->api(array( 'method' => 'fql.query', 'query' => 'select fan_count from page where page_id = 308775617671;' )); echo $fb_fans = '</li><li>'.$result['fan_count'].' likes for battlefield';
If you’d like to automatically add the commas in the numbers (like 1,000,000), just throw
Hope that helps!