Getting social media shares with php

October 9, 2015

Quick snippets to help me (and maybe you!) remember how to quickly and easily get share counts from social networks.

What other networks would you like to see?

Facebook

[php]
function facebook_share_count( $post_id ) {
$api = "https://graph.facebook.com/";

$url = $api . urlencode( get_permalink( $post_id ) );

$response = wp_remote_get( $url );
if( is_wp_error( $response ) ) {
return 0;
}
if( ‘200’ != wp_remote_retrieve_response_code( $response ) ) {
// Bad url
return 0;
}
$body = wp_remote_retrieve_body( $response );
$body = json_decode( $body );
if( isset( $body->shares ) ) {
// Shares will not be set if there are none!
return $body->shares;
}
return 0;
}
[/php]

Twitter

NOTE: ***Twitter will be shutting down this API*** No replacement has been announced.

[php]
function twitter_share_count( $post_id ) {
// Check for transient
if ( ! ( $count = get_transient( ‘twitter_count’ . $post_id ) ) ) {
// Do API call
$response = wp_remote_retrieve_body( wp_remote_get( ‘https://cdn.api.twitter.com/1/urls/count.json?url=’ . urlencode( get_permalink( $post_id ) ) ) );
// If error in API call, stop and don’t store transient
if ( is_wp_error( $response ) )
return ‘error’;
// Decode JSON
$json = json_decode( $response );
// Set total count
$count = absint( $json->count );
// Set transient to expire every 30 minutes
set_transient( ‘twitter_count’ . $post_id, absint( $count ), 30 * MINUTE_IN_SECONDS );
}
return absint( $count );
}
[/php]

LinkedIn

[php]
function linkedin_share_count( $post_id ) {
$api = ‘http://www.linkedin.com/countserv/count/share?format=json&url=’;
$api .= urlencode( get_permalink( $post_id ) );
if ( ! ( $count = get_transient( ‘linkedin_count’ . $post_id ) ) ) {
$response = wp_remote_get( $api );
if( is_wp_error( $response ) ) {
// eat it
return 0;
}
// Should verify the correct json is returned
$json = json_decode( wp_remote_retrieve_body( $response ) );
$count = (int) $json->count;
set_transient( ‘linkedin_count’ . $post_id, absint( $count ), 30 * MINUTE_IN_SECONDS );
}
return $count;
}
[/php]

Leave a Reply

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