Step 1: Create a facebook app
1. Go to Facebook Developers page and click Add a New App link.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 (also add your site's url):
4. The last step is to make your 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: Add the counter to the site
Use the following php function (inside your theme's functions.php):/** * 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; }Call it using:
echo wp_get_shares(get_the_ID());Source: https://rudrastyh.com/facebook/get-share-count-for-url.html#facebook_app
For other social media sources: https://gist.github.com/jonathanmoore/2640302
No comments:
Post a Comment