Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

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

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.


Related Posts:

  1. Changing Social Media
  2. Social sharing is not working as expected
  3. Keeping social share count after changing WordPress Permalinks
  4. Are there any Inbuilt Social media sharing icons
  5. how can I easily clear the “header is malformed” error when trying to reconnect social accounts in jetpack
  6. Social Media Feather icons not displaying for each post
  7. Share buttons in some specific posts in WordPress
  8. how can i display share images for each article?
  9. Post sharing in social network
  10. how to get confirm that a shared user are inivited by member of website?
  11. How to escape echo?
  12. How do I remove social buttons from the “Blog” section of my theme?
  13. Storing posts social counters by using transient api
  14. Default image for homepage when shared in social media
  15. Share buttons on article footer
  16. List repeating share links
  17. Edit Custom Links Menu markup: Making a Social Media Menu with linkable icons
  18. How can i disable a plugin for a mobile phone?
  19. Retrieving Google Plus share count with wp_remote_post
  20. Social sharing post’s shortlink instead of permalink
  21. How to generate “og:image” meta for Facebook sharing when the image in the post is not featured?
  22. Is there a way to change a post’s thumbnail image(s)?
  23. Only display link to author social media when it exists [closed]
  24. Multiple social buttons with a fast loading? [closed]
  25. what function can I use to automatically output og tags per page/post?
  26. Is it possible to use Twitter intents with the post’s image in WordPress?
  27. How to have a “clean” post content, for excerpt and social networks sharing
  28. Automatically add simple custom buttons for print, Facebook share, & Tweet in Posts [closed]
  29. Social sharing toolkit is not showing on ajax load
  30. Add share links to all blog posts on homepage
  31. LinkedIn Social Wall | Is there a plug-in (Free / Paid) to display a LinkedIn feed in a social wall (not just a feed)?
  32. Sharing images to social media – issue with aspect ratio
  33. Modify foreach loop for social sharing links?
  34. buddypress activity social share
  35. How to integrate Facebook Share button without code?
  36. Facebook social publisher and custom post type fields [closed]
  37. Skeleton Child Theme Add Icon Bar to Header Flex Grid
  38. Can i Use own Facebook App ID with this Social Comment Plugin? [closed]
  39. Can I develop a social networking Site using WordPress and its Plugins? [closed]
  40. How to add FB like + share AND also other Social Buttons on ALL pages and posts?
  41. Whenever I am sharing a post wordpress phrase is automatically added, can anyone help?
  42. Post image lacking when pasting link into Facebook despite the correct og:image meta tag
  43. Trouble displaying featured image as thumbnail when using Facebook share
  44. No post image when pasting link into Facebook
  45. how to set social icons to product / post template (Auros theme)? [closed]
  46. How To Post WordPress Custom Post Types to Twitter via IFTTT
  47. add share buttons above my posts without plugins
  48. How to add social follow button to header? [closed]
  49. How to replace URL protocol using PHP?
  50. How to share post?
  51. Social share buttons text shows up on post excerpts
  52. Store SNS share value via function.php
  53. Followers for WordPress [duplicate]
  54. Featured image for social sharing ot author archive page
  55. How to create social Share Buttons Without Plugin
  56. White image when I share my site
  57. How to add extra custom social icons to page with same style?
  58. Author social media aren’t shown on the page
  59. WordPress Sumo Plugin not showing all images on clicking pinterest icon
  60. Featured image not showing on facebook share
  61. Linkedin not returning right info
  62. Social sharing conflict with Rewrite rules
  63. Facebook Share Permalink Javascript href
  64. Social sharing plugin directing to blank page after post sharing
  65. Add Flatr button to Sharing option
  66. Featured Image and Facebook
  67. Is it better to set social media sharer in entry-footer.php or comments.php in WordPress blog?
  68. Facebook and Google+ sharing suddenly stopped working properly in WordPress
  69. Add social media icon in header area
  70. Encode URL picked up by Digg Digg
  71. Slick Social Share Buttons plug-ins with Responsive theme – number of tweets link problem
  72. Using wp_enqueue_script with social media buttons?
  73. Social Sharing / tell a friend plug but specify which URL to share
  74. Facebook share button only share the_permalink(), without thumbnail, tilte, excerpt, etc
  75. Tried everything but Facebook share button won’t load the post thumbnail
  76. What is the best way to change share image for social networks? [closed]
  77. Merge comments from Facebook with WP comments [closed]
  78. Publish post facebook page & twitter automatically [closed]
  79. How properly use social link block in template part
  80. WordPress Share Buttons Plugin: How do you make the WordPress Share Buttons Display Vertically?
  81. WORDPRESS ,Can’t load image of post when sharing post via facebook [closed]
Categories social-sharing Tags social-sharing
How to add custom content (text/image) at start of content (IN content ie the same line)
meta_query date and time comparisons

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress