Misha Rudrastyh made a great guide you can follow here, I’ll include the relevant code here as well.
/*
* 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'] );
$count = intval( $body->share->share_count );
set_transient( $cache_key, $count, 3600 ); // store value in cache for 1 hour
}
return $count;
}
Add this to your theme’s functions.php-file. Now you can use echo wp_get_shares($post->ID);
anywhere you like.