Tracking Facebook Shares on your website or application is a useful way of seeing how popular your articles are with your readers. In order to tracking Shares, you must used the Facebook JavaScript SDK to create the Share popup and then use a callback function to log the result. Use this tutorial to learn how to trigger a callback function to save the result of Shares. In my applications, I use a PHP script (Code Igniter) to save the result to a database.
Important Update:
This tutorial no longer works due to changes with Facebook. In particular, the Share Dialog no longer returns the post_id
in the response, which means shares can no longer be tracked.
The example on JSBin still works, but you will notice that no response is received from Facebook when a post has been shared.
JavaScript Code:
Working Demo:
You can see a working example of the above code on jsbin. If you keep the Console tab open, you will see that the callback function will return the ID of the post, if successfully published on Facebook. This ID can be stored for tracking purposes, and you can make a Facebook API call to the ID (e.g. https://graph.facebook.com/{post_id}
) to get more details about what was posted (you will need read_stream
permission to do so).
The Response:
If the post is successfully shared on Facebook, the callback function will return a response like the following:
You may notice that the post_id
contains the user’s Facebook ID (the 60506094
in the post_id
is my Facebook User ID), which means you know who shared your post. You can make an API call using the user_id
to find public information about the user.
If you have the read_stream
permission for the user, making an API call with the post_id
returned in the callback function will return something like the following:
Ajax Script (PHP):
For reference, the below is an example of the PHP script I’ve used in my Facebook applications to log any shares to a database.
The Result:
The share to the user’s timeline will look like any other. Here is what will appear on your timeline if you use the above code: