$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>Get total social share count (Facebook, Twitter, Google+. Pinterest)|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Get total social share count (Facebook, Twitter, Google+. Pinterest)

matteradmin7PV0评论

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( '/?id=' . $url );

    $count = json_decode( $api );

    return $count->shares;
};

$twitter_tweet_count = function ( $url ) {

    $api = file_get_contents( '.json?url=' . $url );

    $count = json_decode( $api );

    return $count->count;
};

$pinterest_pins = function ( $url ) {

    $api = file_get_contents( '.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, "" );
    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!

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/?id=' . $url );

    $count = json_decode( $api );

    return $count->shares;
};

$twitter_tweet_count = function ( $url ) {

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

    $count = json_decode( $api );

    return $count->count;
};

$pinterest_pins = function ( $url ) {

    $api = file_get_contents( 'http://api.pinterest/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/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!

Share Improve this question edited May 28, 2015 at 15:50 japanworm asked May 24, 2015 at 18:10 japanwormjapanworm 5873 gold badges19 silver badges40 bronze badges 11
  • 3 $total_count = $facebook_like_share_count + $twitter_tweet_count + $pinterest_pins + $google_plusones; – Nicolai Grossherr Commented May 26, 2015 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 Commented May 26, 2015 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 Commented May 26, 2015 at 23:47
  • 1 @ialocin Transients! Yes! I will need to update my own code now. OP, see: codex.wordpress/Transients_API – Christine Cooper Commented May 27, 2015 at 15:38
  • 1 @ialocin I just hit up an answer to this using transients. Nice one. – Christine Cooper Commented May 27, 2015 at 16:18
 |  Show 6 more comments

1 Answer 1

Reset to default 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/?id=' . $url );

        $count = json_decode( $api );

        return $count->shares;
    };

    $twitter_tweet_count = function ( $url ) {

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

        $count = json_decode( $api );

        return $count->count;
    };

    $pinterest_pins = function ( $url ) {

        $api = file_get_contents( 'http://api.pinterest/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/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.

Post a comment

comment list (0)

  1. No comments so far