2

I'm pulling the individual share counts for the social media I've mentioned using the following code snippet in my theme's function.php:

$facebook_like_share_count = function ( $url ) {

    $api = file_get_contents( 'http://graph.facebook.com/?id=' . $url );

    $count = json_decode( $api );

    return $count->shares;
};

$twitter_tweet_count = function ( $url ) {

    $api = file_get_contents( 'https://cdn.api.twitter.com/1/urls/count.json?url=' . $url );

    $count = json_decode( $api );

    return $count->count;
};

$pinterest_pins = function ( $url ) {

    $api = file_get_contents( 'http://api.pinterest.com/v1/urls/count.json?callback%20&url=' . $url );

    $body = preg_replace( '/^receiveCount\((.*)\)$/', '\\1', $api );

    $count = json_decode( $body );

    return $count->count;

};

$google_plusones = function ( $url ) {
    $curl = curl_init();
    curl_setopt( $curl, CURLOPT_URL, "https://clients6.google.com/rpc" );
    curl_setopt( $curl, CURLOPT_POST, 1 );
    curl_setopt( $curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]' );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Content-type: application/json' ) );
    $curl_results = curl_exec( $curl );
    curl_close( $curl );
    $json = json_decode( $curl_results, true );

    return intval( $json[0]['result']['metadata']['globalCounts']['count'] );
};

I'm calling them into my single.php with the following code:

<?php $url = get_permalink( $post_id ); echo $facebook_like_share_count ("$url");?>
<?php $url = get_permalink( $post_id ); echo $twitter_tweet_count ("$url");?>
<?php $url = get_permalink( $post_id ); echo $pinterest_pins ("$url");?>
<?php $url = get_permalink( $post_id ); echo $google_plusones ("$url");?>

This works fine.

Now, I'm trying to find a code snippet that will add the share count of those 4 services and shows the total share count - probably something similar to this here.

EDIT: I have an important question.

Is it possible that the code above is slowing down my blog?

I've already contacted my hosting service and they told me it must be something like a plugin or php files. I haven't really updated any plugins recently and P3 Profilier just tells me who the usual culprits are. But I noticed right after calling that function in my single.php my server sometimes loads super slow - even gets timeouts on speed checking sites. Any ideas?

EDIT2: After a lot of testing it really seems to be this code (when echoed) that slows down the page. shrugs Guess I have to stop using it?

I haven't been able to get it to work yet. I hope you can help me out here. Thank you so much!

  • 3
    $total_count = $facebook_like_share_count + $twitter_tweet_count + $pinterest_pins + $google_plusones; – Nicolai May 26 '15 at 14:02
  • @ialocin Can I just copy and paste that into my function.php as is and echo it into my single.php? Thank you. :) – japanworm May 26 '15 at 21:15
  • The reason why it is slowing down your page is because you are requesting data from 4 different sites. So all of those needs to be loaded before your script continues to process. This is bad. Add a cron that does this for you, or cache the page. Don't load this on every page load. – Christine Cooper May 26 '15 at 23:47
  • 1
    @ialocin Transients! Yes! I will need to update my own code now. OP, see: codex.wordpress.org/Transients_API – Christine Cooper May 27 '15 at 15:38
  • 1
    @ialocin I just hit up an answer to this using transients. Nice one. – Christine Cooper May 27 '15 at 16:18
3

Okay. @ialocin made a note about Transients. By some odd reason, I have not come across this yet. Previously, I used to display counts by:

  • jQuery (client side loading)
  • Page caching (when storing counts locally)
  • Cron updating count values
  • And most recently, stored all counts in post meta and updated the meta every 100 loading of the page... pretty wild.

But no, there is something better. I lot better. Transients. Transients. Transients... chant it for hours... Once you've meditate and returned, delve into the following code which I customized for you:

// Check for transient. If none, then execute code
if ( false === ( $data = get_transient( 'trans_' . $post_id ) ) ) {

    /* action */
    $facebook_like_share_count = function ( $url ) {

        $api = file_get_contents( 'http://graph.facebook.com/?id=' . $url );

        $count = json_decode( $api );

        return $count->shares;
    };

    $twitter_tweet_count = function ( $url ) {

        $api = file_get_contents( 'https://cdn.api.twitter.com/1/urls/count.json?url=' . $url );

        $count = json_decode( $api );

        return $count->count;
    };

    $pinterest_pins = function ( $url ) {

        $api = file_get_contents( 'http://api.pinterest.com/v1/urls/count.json?callback%20&url=' . $url );

        $body = preg_replace( '/^receiveCount\((.*)\)$/', '\\1', $api );

        $count = json_decode( $body );

        return $count->count;

    };

    $google_plusones = function ( $url ) {
        $curl = curl_init();
        curl_setopt( $curl, CURLOPT_URL, "https://clients6.google.com/rpc" );
        curl_setopt( $curl, CURLOPT_POST, 1 );
        curl_setopt( $curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]' );
        curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Content-type: application/json' ) );
        $curl_results = curl_exec( $curl );
        curl_close( $curl );
        $json = json_decode( $curl_results, true );

        return intval( $json[0]['result']['metadata']['globalCounts']['count'] );
    };

    // store data in array
    $data = array (
        $facebook_like_share_count,
        $twitter_tweet_count,
        $pinterest_pins,
        $google_plusones
    );

    // Put the results in a transient. Expire after 6 hours
    set_transient( 'trans_' . $post_id, $data, 6 * HOUR_IN_SECONDS  );
}

if (is_array($data)) {

    $facebook_like_share_count = $data[0];
    $twitter_tweet_count = $data[1];
    $pinterest_pins = $data[2];
    $google_plusones = $data[3];

}

Firstly, make sure that $post_id is already set previously to adding this code as it uses the ID to add a unique handle to the transient.

We are storing cached data in the database temporarily by giving it a custom name and a timeframe after which it will expire and be deleted.

So, for every 6 hours, it updates the cached array. It's as simple as that. See the comments for clarification.

EDIT:

As per discussions in the comment thread, I have adjusted the code. Firstly, make sure you have the share functions inside your functions.php file (I believe you already have this in your current setup), then in your single.php file, add the following where you want to get the count values.

// get post id
$post_id = get_the_ID();

// get perm url to be used for share count functions
$url = get_permalink( $post_id );

// Check for transient. If none, then execute code
if ( false === ( $data = get_transient( 'trans_' . $post_id ) ) ) {

    /* action */
    $facebook_like_share_count ("$url");
    $twitter_tweet_count ("$url");
    $pinterest_pins ("$url");
    $google_plusones ("$url");

    // store data in array
    $data = array (
        $facebook_like_share_count,
        $twitter_tweet_count,
        $pinterest_pins,
        $google_plusones
    );

    // Put the results in a transient. Expire after 6 hours
    set_transient( 'trans_' . $post_id, $data, 6 * HOUR_IN_SECONDS  );
}

if (is_array($data)) {

    // these are your variables containing the share count
    $facebook_like_share_count = $data[0];
    $twitter_tweet_count = $data[1];
    $pinterest_pins = $data[2];
    $google_plusones = $data[3];

}

Please read the comments I put inside the code for clarification.

  • 1
    You just made me smile happily with how happy transients make you :) – Nicolai May 27 '15 at 20:08
  • Hello. Thank you so much for your hard work. I tried to put your code into my theme's function.php, but if I do so my page won't load. I suppose there's a syntax error? :( – japanworm May 27 '15 at 21:27
  • What? No, this code should go whereever it was originally taken from. I am guessing single.php – Christine Cooper May 27 '15 at 21:29
  • @ChristineCooper I had the code I originally posted in my question in my function.php and then echoed it into single.php. I though I was supposed to do the same with your code snippet?! ^^; – japanworm May 28 '15 at 8:52
  • 1
    file_get_contents() will not work with URLs on all servers. Use the HTTP API instead. – fuxia May 30 '15 at 3:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.