NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Display the Number of Facebook Shares for a Page or Post
Intermediate

---- Last modified : Nov 18 2021

Estimated reading time : 1 minute, 50 seconds - 183 words

With this tutorial we will show you how to display the number of share of a WordPress page or post on Facebook. The first step will be creating an API via Facebook developpers.

Once you’ve created your API, go into the left hand side menu under Settings –> General. This is where you’ll find the APP ID and your secret passkey. You can also fill out additional important information such as websites authorized to use this app among other useful information.

Afterwards, you’ll need to add a function that will allow the API to count the number of Facebook shares of the WordPress post via its ID. You’ll need to add it into your functions.php file:

function wp_get_shares_facebook( $post_id ) {
	$cache_key = 'toni_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( add_query_arg( array( 
			'id'               => urlencode( get_permalink( $post_id ) ),
			'access_token'     => $access_token,
			'fields'           => 'engagement'
		), 'https://graph.facebook.com/v3.0/' ) );
		
		$body = json_decode( $response['body'] );
		//print_r($body);
 
		$count = intval( $body->engagement->share_count ); 
 
		set_transient( $cache_key, $count, 3600 ); // store value in cache for a 1 hour
	}
	return $count;
}

Next to $access_token = ‘APP_ID|APP_SECRET’, you’ll need to replace APP_ID by your API’s ID and then replace APP_SECRET by the secret passkey.

Once your function is ready to go, we will display the result in desired area of your template; all you need to do is call the current post ID to display its number of Facebook shares.

<?php $id = get_the_ID(); echo wp_get_shares_facebook( $id ); ?>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>