3 Ways of Getting Shares for URL using Facebook 2.7 API

In this tutorial I will show you 3 examples of getting Facebook shares using the new Graph API – cURL PHP example, WordPress HTTP API example and only jQuery example.

#facebook, #Facebook, #httpapi  /  July 3  /   16

No matter what way you choose, in any case you should make a little preparation — create a Facebook App and get Access Token from it (App ID|App Secret).

Step 1. Creating Facebook App #

1. Go to Facebook Developers page and click Add a New App link.

Facebook Applications List. Ann a new app.

2. After clicking that link a popup will appear. Input any App Name, your Contact Email and select Category.

3. Get App ID and App Secret on this page:

How to get Facebook Application ID and Secret

4. The last step is to make your facebook application public.

How to make Facebook Application Public

So, that’s it, in all examples in this post our Access Token will look like this: Application ID|App Secret.

Step 2. Get Shares Count. Ready-to-use Examples. #

WordPress, cURL and jQuery examples are below.

WordPress HTTP API example #

If you are not familiar with WordPress, insert the following code to the functions.php file of your active theme.

/**
 * Display number of shares using WordPress HTTP API
 *
 * @param integer $post_id We want to get number of shares of the post with this ID
 */
function wp_get_shares( $post_id ) {
	$cache_key = 'misha_share' . $post_id;
	$access_token = 'APP_ID|APP_SECRET';
	$count = get_transient( $cache_key ); // try to get value from Wordpress cache
 
	// if no value in the cache
	if ( $count === false ) {
		$response = wp_remote_get('https://graph.facebook.com/v2.7/?id=' . urlencode( get_permalink( $post_id ) ) . '&access_token=' . $access_token );
		$body = json_decode( $response['body'] );
		//print_r($body);
 
		$count = intval( $body->share->share_count );
		set_transient( $cache_key, $count, 3600 ); // store value in cache for a 1 hour
	}
	return $count;
}

If you add this function to your functions.php you can now freely use it anywhere in your theme files like this:

echo wp_get_shares( 355 );

cURL example #

Function:

/**
 * Display number of shares using PHP cURL library
 *
 * @param string $url ID We want to get number of shares of this URL
 */
function curl_get_shares( $url ){
	$access_token = 'APP ID|APP SECRET';
	$api_url = 'https://graph.facebook.com/v2.7/?id=' . urlencode( $url ) . '&access_token=' . $access_token;
	$fb_connect = curl_init(); // initializing
	curl_setopt( $fb_connect, CURLOPT_URL, $api_url );
	curl_setopt( $fb_connect, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
	curl_setopt( $fb_connect, CURLOPT_TIMEOUT, 20 );
	$json_return = curl_exec( $fb_connect ); // connect and get json data
	curl_close( $fb_connect ); // close connection
	$body = json_decode( $json_return );
	return intval( $body->share->share_count );
}

Usage:

echo curl_get_shares( 'https://rudrastyh.com/api/get-facebook-shares.html' );

jQuery example with live demo #

Well, I hope you know what is jQuery and how to work with it. Here is the code and there is a live demo below.

var token = 'APP ID|APP SECRET', // learn how to obtain it above
url = 'YOUR URL';
 
$.ajax({
	url: 'https://graph.facebook.com/v2.7/',
	dataType: 'jsonp',
	type: 'GET',
	data: {access_token: token, id: url},
	success: function(data){
 		console.log(data);
 		$('body').append(data.share.share_count);
	},
	error: function(data){
		console.log(data); // send the error notifications to console
	}
});

See the Pen grVGvk by Misha (@rudrastyh) on CodePen.light

Only the best of WordPress

Subscribe to this weekly newsletter to receive the latest blog posts by email.I respect your privacy. Your email is safe with me.

Comments 16

  • Thanks, friend.

  • thanks a lot
    I spend an entire day looking for this

  • Thanks! This is what I looking for since facebook start to use API 2.7

  • I can’t share this post on Facebook with your share button. It says: App Not Setup: This app is still in development mode, and you don’t have access to it. Switch to a registered test user or ask an app admin for permissions.

  • Sorry, but this doesn’t get the share count. It actually gets “likes, shares and comments” combined.

    It’s a shame facebook no longer allows you to get each individual #.

  • How without Access Token?
    Url for example:

    $paramsURL = self::_parse("https://graph.facebook.com/?fields=og_object{likes.limit(0).summary(true)},share&ids=".urlencode($this->urlData['url']));
  • can you input a wp code without saving to database? it creates a huge load on the server
    thanks

    • MishaAuthor January 4, 2017 at 11:28

      Hi Mike,

      do you mean set_transient() ? Are you sure about huge load?

      Anyway, if you do not want to use cache, you can remove lines 7, 9,12,18,19

  • Thank you this is exactly what I needed!

  • Thanks, It works!

  • Hi,

    Thanks for the code. I have tried to add my own APP ID|APP SECRET, but in the returned array there are no share infos.

    Array with my access_token:
    stdClass Object ( [og_object] => stdClass Object ( [id] => 1511323895597932 [description] => Loaves on loaves on loaves [title] => The Great British Baking Show Episode 3: Bread! [type] => article [updated_time] => 2017-06-26T19:55:46+0000 ) [id] => https://food52.com/blog/19948-the-great-british-baking-show-episode-3-bread )

    Array with yours access_token:
    stdClass Object ( [share] => stdClass Object ( [comment_count] => 0 [share_count] => 236 ) [id] => https://food52.com/blog/19948-the-great-british-baking-show-episode-3-bread )

    How can I use my access_token to get share infos?

    Thanks,
    Peter

    • MishaAuthor July 6, 2017 at 09:40

      Hi Peter,

      I’m not sure why this happens, I’ve just tested it with my different apps and every time I got the correct number of shares

  • How could I save the number as meta (and updated now and then)?

    • MishaAuthor July 7, 2017 at 21:40

      Hello,

      Just below the line 18 in the first code example add something like this:

      update_post_meta( $post_id, 'facebook_share_count', $count );

Leave your question or feedback

phpjsHTMLCSSSQLCode
Please, enter a comment
Please, enter a name
Incorrect email