Custom Social Media Buttons for WordPress with Share Count (including Google+)

Update 3: I wrote a whole new tutorial for the custom sharing buttons. This new version loads asynchronously to speed up the page speed noticeably. Check it out: Custom Share Buttons with Sharrre

Update 2: As requested, the template now also includes a share button for LinkedIn with count.

Update: The Google+ Count is now cached as well and I added Flattr to the list of included buttons.

When you want share buttons for your website you are widely advised to use the “factory-default” versions supplied by Facebook, Twitter and Google+. These, in their most minimal version, look like this:

Share Buttons

There are a few things, which led me to develop custom social share buttons for wordpress instead of these buttons:

  • German Authorities actually kind of forbid the use of the like-button from Facebook, because it collects private data without the user accepting this behaviour.
  • They impact the performance of your website. Although Facebook made theirs faster recently 0.5s load-time is still pretty bad for the page speed.
  • I don’t really like the look of the buttons. They each have their own look and don’t integrate well into every webdesign.
  • A lot of people have the same problem and search for a custom facebook share buttons or custom twitter share buttons

Enough pretext, here’s what I came up with:

Custom WordPress Share Buttons

Why do I like those?

  • Custom Social Share buttons with Share Count.
  • Unified unobtrusive look, easily stylable.
  • Simple Share Links, no data is collected.
  • They load much faster.

I’m no programmer so I made those work as usual by putting my copy & paste – programming – skills to work.

These 4 steps make the buttons work:

  1. The Code for your themes function.php to get the counter work.
  2. A little script that takes care of sizing an positioning the popups
  3. The Font Awesome Icon Set (for the Social Icons)
  4. The CSS Code to style those Buttons.

1. The Code for your function.php

I found this great post by webdev studios showing me how to grab the like count from facebook and twitter. Unfortunately I was out of luck for the Google+ Share Count. But after some research I found this blogpost on how to get the share count for Google Plus. I combined those, and it works. Update: I’ve seen some unsolved questions on how to customize the flattr button, so I added a custom flattr Button without javascript here as well. Just delete the corresponding parts in the code, if you don’t need it.

Put this code at the end of your functions.php

 
 
/** Get tweet count from Twitter API (v1.1) */
 
function ds_post_tweet_count( $post_id ) {
 
  // Check for transient
  if ( ! ( $count = get_transient( 'ds_post_tweet_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( 'ds_post_tweet_count' . $post_id, absint( $count ), 30 * MINUTE_IN_SECONDS );
 
  }
 
 return absint( $count );
 
}  /** Twitter End */
 
 
/** Get like count from Facebook FQL  */
 
function ds_post_like_count( $post_id ) {
 
  // Check for transient
  if ( ! ( $count = get_transient( 'ds_post_like_count' . $post_id ) ) ) {
 
    // Setup query arguments based on post permalink
    $fql  = "SELECT url, ";
    //$fql .= "share_count, "; // total shares
    //$fql .= "like_count, "; // total likes
    //$fql .= "comment_count, "; // total comments
    $fql .= "total_count "; // summed total of shares, likes, and comments (fastest query)
    $fql .= "FROM link_stat WHERE url = '" . get_permalink( $post_id ) . "'";
 
    // Do API call
    $response = wp_remote_retrieve_body( wp_remote_get( 'https://api.facebook.com/method/fql.query?format=json&query=' . urlencode( $fql ) ) );
 
    // 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[0]->total_count );
 
    // Set transient to expire every 30 minutes
    set_transient( 'ds_post_like_count' . $post_id, absint( $count ), 30 * MINUTE_IN_SECONDS );
 
  }
 
 return absint( $count );
 
} /** Facebook End  */
 
 
/** Get share count from Google Plus */
 
function ds_post_plusone_count($post_id) {
 
	// Check for transient
	if ( ! ( $count = get_transient( 'ds_post_plus_count' . $post_id ) ) ) {
 
	    $args = array(
	            'method' => 'POST',
	            'headers' => array(
	                // setup content type to JSON 
	                'Content-Type' => 'application/json'
	            ),
	            // setup POST options to Google API
	            'body' => json_encode(array(
	                'method' => 'pos.plusones.get',
	                'id' => 'p',
	                'method' => 'pos.plusones.get',
	                'jsonrpc' => '2.0',
	                'key' => 'p',
	                'apiVersion' => 'v1',
	                'params' => array(
	                    'nolog'=>true,
	                    'id'=> get_permalink( $post_id ),
	                    'source'=>'widget',
	                    'userId'=>'@viewer',
	                    'groupId'=>'@self'
	                ) 
	             )),
	             // disable checking SSL sertificates               
	            'sslverify'=>false
	        );
 
	    // retrieves JSON with HTTP POST method for current URL  
	    $json_string = wp_remote_post("https://clients6.google.com/rpc", $args);
 
	    if (is_wp_error($json_string)){
	        // return zero if response is error                             
	        return "0";             
	    } else {        
	        $json = json_decode($json_string['body'], true);                    
	        // return count of Google +1 for requsted URL
	        $count = intval( $json['result']['metadata']['globalCounts']['count'] ); 
	    }
 
	    // Set transient to expire every 30 minutes
		set_transient( 'ds_post_plus_count' . $post_id, absint( $count ), 30 * MINUTE_IN_SECONDS );
 
	}
 
	return absint( $count );    
} /** Google Plus End */
 
 
/** Get Flattr count */
 
function ds_post_flattr_count( $post_id ) {
 
  // Check for transient
  if ( ! ( $count = get_transient( 'ds_post_flattr_count' . $post_id ) ) ) {
 
    // Check if URL exists
    $response = wp_remote_retrieve_body( wp_remote_get( 'https://api.flattr.com/rest/v2/things/lookup/?url=' . urlencode( get_permalink( $post_id ) ) ) );
 
    // Decode JSON
    $json = json_decode( $response );
 
	// Get URL ID
	$message = $json->message;
 
	if ($message == "not_found") {
      return 0;
	}
 
	else {
		$location = $json->location;
		$flattrs = $json->flattrs;
		$count = $flattrs;
	}
 
	// Set transient to expire every 30 minutes
	set_transient( 'ds_post_flattr_count' . $post_id, absint( $count ), 30 * MINUTE_IN_SECONDS );
 
  }
 
 return absint( $count );
 
} /** Flattr End */
 
 
/** Get Count from LinkedIn */
 
function ds_post_linkedin_count( $post_id ) {
 
  // Check for transient
  if ( ! ( $count = get_transient( 'ds_post_linkedin_count' . $post_id ) ) ) {
 
    // Do API call
    $response = wp_remote_retrieve_body( wp_remote_get( 'https://www.linkedin.com/countserv/count/share?url=' . urlencode( get_permalink( $post_id ) ) . '&format=json' ) );
 
    // 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( 'ds_post_linkedin_count' . $post_id, absint( $count ), 30 * MINUTE_IN_SECONDS );
 
  }
 
 return absint( $count );
 
}  /** LinkedIn End */
 
 
/** Markup for Social Media Icons */
 
function ds_social_media_icons() {
 
  // Get the post ID
  $post_id = get_the_ID(); ?>
 
  <div class="social-icons-wrap">
	<ul class="social-icons">
		<!-- Facebook Button-->
		<li class="social-icon facebook">
			<a onclick="javascript:popupCenter('https://www.facebook.com/sharer/sharer.php?u=<?php the_permalink(); ?>&amp;appId=XXX_YOUR_FACEBOOK_APP_ID','Facebook Share', '540', '400');return false;" href="https://www.facebook.com/sharer/sharer.php?u=<?php the_permalink(); ?>&amp;appId=XXX_YOUR_FACEBOOK_APP_ID" target="blank"><i class="fa fa-facebook"></i> Share </a><span class="share-count"><?php echo ds_post_like_count( $post_id ); ?></span>
		</li>
		<!-- Twitter Button -->
		<li class="social-icon twitter">
			<a onclick="javascript:popupCenter('https://twitter.com/share?&amp;url=<?php the_permalink(); ?>&amp;text=<?php the_title(); ?>&amp;via=XXX_YOUR_TWITTER_HANDLE','Tweet', '540', '400');return false;" href="https://twitter.com/share?&amp;url=<?php the_permalink(); ?>&amp;text=<?php the_title(); ?>&amp;via=XXX_YOUR_TWITTER_HANDLE" target="blank"><i class="fa fa-twitter"></i> Tweet </a><span class="share-count"><?php echo ds_post_tweet_count( $post_id ); ?></span>
		</li>
		<!-- Google + Button-->
		<li class="social-icon google-plus">
			<a onclick="javascript:popupCenter('https://plus.google.com/share?url=<?php the_permalink(); ?>','Share on Google+', '600', '600');return false;" href="https://plus.google.com/share?url=<?php the_permalink(); ?>" target="blank"><i class="fa fa-google-plus"></i> Google+</a><span class="share-count"><?php echo ds_post_plusone_count( $post_id ); ?></span>
		</li>
		<!-- Flattr Button-->
		<li class="social-icon flattr">
			<a onclick="javascript:popupCenter('https://flattr.com/submit/auto?user_id=XXX_YOUR_FLATTR_ID&url=<?php echo urlencode(get_permalink($post->ID)); ?>&title=<?php echo rawurlencode(strip_tags(get_the_title())) ?>&language=de_DE&&category=text','Support with Flattr', '680', '400');return false;" href="https://flattr.com/submit/auto?user_id=XXX_YOUR_FLATTR_ID&url=<?php echo urlencode(get_permalink($post->ID)); ?>&title=<?php echo rawurlencode(strip_tags(get_the_title())) ?>&language=de_DE&&category=text" target="blank" rel="nofollow">Flattr</a><span class="share-count"><?php echo ds_post_flattr_count( $post_id ); ?></span>
		</li>
		<!-- LinkedIn Button -->
		<li class="social-icon linkedin">
			<a onclick="javascript:popupCenter('http://www.linkedin.com/shareArticle?mini=true&amp;url=<?php the_permalink(); ?>&amp;title=<?php the_title(); ?>&amp;source=<?php site_url(); ?>','Share on LinkedIn', '520', '570');return false;" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=<?php the_permalink(); ?>&amp;title=<?php the_title(); ?>&amp;source=<?php site_url(); ?>" target="blank"><i class="fa fa-linkedin"></i> LinkedIn </a><span class="share-count"><?php echo ds_post_linkedin_count( $post_id ); ?></span>
		</li>
	</ul>
  </div><!-- .social-icons-wrap -->
 
<?php }

At the end I marked some stuff with XXX, be sure to fill those in accordingly. You can generate your facebook app_ID over at the Dev Center for Facebook. (Apps ▸ Create new App). The via=XXX in the twitter section should obviously be filled with your twitter name. The Flattr User Id is pretty self-explanatory.

2. Centering the Popups

The following script takes care of positioning and sizing simple sharing popup dialogs.

var popupCenter = function(url, title, w, h) {
        // Fixes dual-screen position                         Most browsers      Firefox
        var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
        var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;
 
        var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
        var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
 
        var left = ((width / 2) - (w / 2)) + dualScreenLeft;
        var top = ((height / 3) - (h / 3)) + dualScreenTop;
 
        var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
 
        // Puts focus on the newWindow
        if (window.focus) {
            newWindow.focus();
        }
    };

Put this script somewhere above your first sharing buttons. Presumably you just put the script on your server as a .js file and call it like so:

<script src="/wp-content/themes/yourtheme/js/popup.js"></script>

3. Icons from Font Awesome (optional)

Quickly implement number 3 on our list. Font Awesome lets you use a wide range of social icons with simple markup. I use the service in my markup, so you might as well. Just implement this call in the Head-Area of your theme:

4. Styling the Buttons

The last step, number 4, is to style your Buttons accordingly. Here is the CSS-Code I use. Just put it in your style.css file. You can of course edit this code to reflect your blog/websites look.

/* General Social Button Styling */
.social-icons {
	height: 25px;
}
 
.social-icons li {
	list-style-type: none !important;
	float: left;
	margin-top: 10px;
	margin-right: 10px;
	margin-bottom: 10px;
	margin-left: 0 !important;
	font-size: 12px !important;
	font-weight: bold !important;
}
 
.social-icons li:last-child {
	margin-right: 0 !important;
}
 
/* Facebook Button Styling */
li.social-icon.facebook a {
	border-top: 1px solid #3b5998;
	border-left: 1px solid #3b5998;
	border-bottom: 1px solid #3b5998;
	padding: 3px 5px 3px 15px;
	-webkit-border-top-left-radius: 3px;
	border-top-left-radius: 3px;
	-webkit-border-bottom-left-radius: 3px;
	border-bottom-left-radius: 3px;
	color: #3b5998;
	font-family: 'Helvetica Neue', Helvetica, Arial, 'lucida grande', tahoma, verdana, arial, sans-serif;
	text-decoration: none;
}
 
li.social-icon.facebook a:hover {
	background-color: #3b5998;
	color: white;
}
 
li.social-icon.facebook span.share-count {
	border: 1px solid #3b5998;
	padding: 3px 10px;
	-webkit-border-top-right-radius: 3px;
	border-top-right-radius: 3px;
	-webkit-border-bottom-right-radius: 3px;
	border-bottom-right-radius: 3px;
	color: #3b5998;
	font-family: 'Helvetica Neue', Helvetica, Arial, 'lucida grande', tahoma, verdana, arial, sans-serif;
}
 
/* Twitter Button Styling */
li.social-icon.twitter a {
	border-top: 1px solid #55acee;
	border-left: 1px solid #55acee;
	border-bottom: 1px solid #55acee;
	padding: 3px 5px 3px 15px;
	-webkit-border-top-left-radius: 3px;
	border-top-left-radius: 3px;
	-webkit-border-bottom-left-radius: 3px;
	border-bottom-left-radius: 3px;
	color: #55acee;
	font-family: 'Helvetica Neue', Helvetica, Arial, 'lucida grande', tahoma, verdana, arial, sans-serif;
	text-decoration: none;
}
 
li.social-icon.twitter a:hover {
	background-color: #55acee;
	color: white;
}
 
li.social-icon.twitter span.share-count {
	border: 1px solid #55acee;
	padding: 3px 10px;
	-webkit-border-top-right-radius: 3px;
	border-top-right-radius: 3px;
	-webkit-border-bottom-right-radius: 3px;
	border-bottom-right-radius: 3px;
	color: #55acee;
	font-family: 'Helvetica Neue', Helvetica, Arial, 'lucida grande', tahoma, verdana, arial, sans-serif;
}
 
/* Google+ Button Styling */
li.social-icon.google-plus a {
	border-top: 1px solid #dd4b39;
	border-left: 1px solid #dd4b39;
	border-bottom: 1px solid #dd4b39;
	padding: 3px 5px 3px 15px;
	-webkit-border-top-left-radius: 3px;
	border-top-left-radius: 3px;
	-webkit-border-bottom-left-radius: 3px;
	border-bottom-left-radius: 3px;
	color: #dd4b39;
	font-family: 'Helvetica Neue', Helvetica, Arial, 'lucida grande', tahoma, verdana, arial, sans-serif;
	text-decoration: none;
}
 
li.social-icon.google-plus a:hover {
	background-color: #dd4b39;
	color: white;
}
 
li.social-icon.google-plus span.share-count {
	border: 1px solid #dd4b39;
	padding: 3px 10px;
	-webkit-border-top-right-radius: 3px;
	border-top-right-radius: 3px;
	-webkit-border-bottom-right-radius: 3px;
	border-bottom-right-radius: 3px;
	color: #dd4b39;
	font-family: 'Helvetica Neue', Helvetica, Arial, 'lucida grande', tahoma, verdana, arial, sans-serif;
}
 
/* Flattr Button Styling */
li.social-icon.flattr a {
	border-top: 1px solid #338d11;
	border-left: 1px solid #338d11;
	border-bottom: 1px solid #338d11;
	padding: 3px 5px 3px 15px;
	-webkit-border-top-left-radius: 3px;
	border-top-left-radius: 3px;
	-webkit-border-bottom-left-radius: 3px;
	border-bottom-left-radius: 3px;
	color: #338d11;
	font-family: 'Helvetica Neue', Helvetica, Arial, 'lucida grande', tahoma, verdana, arial, sans-serif;
	text-decoration: none;
}
 
li.social-icon.flattr a:hover {
	background-color: #338d11;
	color: white;
}
 
li.social-icon.flattr span.share-count {
	border: 1px solid #338d11;
	padding: 3px 10px;
	-webkit-border-top-right-radius: 3px;
	border-top-right-radius: 3px;
	-webkit-border-bottom-right-radius: 3px;
	border-bottom-right-radius: 3px;
	color: #338d11;
	font-family: 'Helvetica Neue', Helvetica, Arial, 'lucida grande', tahoma, verdana, arial, sans-serif;
}
 
/* LinkedIn Button Styling */
 
li.social-icon.linkedin a {
	border-top: 1px solid #0976b4;
	border-left: 1px solid #0976b4;
	border-bottom: 1px solid #0976b4;
	padding: 3px 5px 3px 15px;
	-webkit-border-top-left-radius: 3px;
	border-top-left-radius: 3px;
	-webkit-border-bottom-left-radius: 3px;
	border-bottom-left-radius: 3px;
	color: #0976b4;
	font-family: 'Helvetica Neue', Helvetica, Arial, 'lucida grande', tahoma, verdana, arial, sans-serif;
	text-decoration: none;
}
 
li.social-icon.linkedin a:hover {
	background-color: #0976b4;
	color: white;
}
 
li.social-icon.linkedin span.share-count {
	border: 1px solid #0976b4;
	padding: 3px 10px;
	-webkit-border-top-right-radius: 3px;
	border-top-right-radius: 3px;
	-webkit-border-bottom-right-radius: 3px;
	border-bottom-right-radius: 3px;
	color: #0976b4;
	font-family: 'Helvetica Neue', Helvetica, Arial, 'lucida grande', tahoma, verdana, arial, sans-serif;
}

Last step: You need to call the function from your functions.php to display the share buttons. You can use this code either on your post page or also on your homepage (the loop), just put it into your themes post/loop-template wherever you want to display the buttons:

<?php ds_social_media_icons(); ?>

That’s it, those are my custom social share buttons for wordpress with share count. Hope that helps somebody out there when trying to figure out how to get share counts on Google+, Facebook and Twitter Buttons in WordPress. It works well for me … try them if you like this post.

Buy me a beer: If you’ll use this download, I’d appreciate a small token of appreciation to keep this blog up and running (and keep it clean of ads).

35 Kommentare

Füge deinen hinzu →

  1. Wow! This is an awesome tutorial, it makes me wonder why nobody is writing an awesome comment about it! I hate social media plugins because they are often hard to style, thank you so much for this!

  2. how to add my facebook, google+, twitter sharing link

  3. We can add social media buttons on every post in wordpress without plugins.

    Please check that link for Trick.

    http://www.themesrefinery.com/add-wordpress-social-media-buttons-without-plugin/

  4. This is very cool. Trying it now. Do you have code for Linkedin as well by any chance?

  5. Very well explained without going too draggy. „)

  6. I’ve been redesigning my whole site (started off by this article) and it all seems to work fine, except I can’t get the social share buttons‘ counts to work on the homepage itself. they keep picking up the id of the first blog post eventhough I’ve changed „$post_id“ to „$front_page_id“

    Any ideas?

  7. Awesome. Thanks. Did you try searching for a Linkedin button as well ?

  8. Hi Daniel

    Please refer to the attached image. What could possibly be the issue here?

    PS: Honestly, this is one of, if not, the best custom social media icons + count I’ve seen so far. Good job, really.

    • I think the problem lies in the local installation. I’m using set_transient to cache the share counts, probably this operation can’t be done locally. I’m guessing that is the case because I just recently added the caching to G+ as well, as this one works it’s got to be this part of the code that throws the error. Hope that helps … Thanks also for your kind words!

  9. i have another challenge for you, which i’m currently trying to figure out on my side. Would it be possible to call this function after page load, or at least call it last it the script ? The reason I’m looking for this is that the function considerably slows down page load time, and if it’s place above content, then the content takes a while to show up on the screen. The only + side on „normal“ social icons is that they load asynchronously…

  10. CharfishCharlie

    7. November 2014 — 22:26

    Awesome work! Using these on one of my sites right now. Easy to use, and a breeze to customize.

  11. I really like the look of these a lot! Can the color be changed, too? And this may be the worst question you’ve ever gotten, but I’m having trouble even figuring out WHERE to put this code in my WP backend. Hehe. I know that’s bad, but if you can tell me where to go exactly to enter this code, I will probably be able to figure out the rest (with my husband’s help)! 🙂

  12. Hey Daniel, I’m having trouble with Pinterest. When using this code, Pinterest never finds an image to share. Here’s a Genesis site with Yoast SEO: http://birthanarchy.com/diane-rehm-show-perpetuates-silencing-women/#

    Here’s a WooTheme site with Add Meta Data: http://omasattic.net/product/509/#

    Both sites run on cloudflare and use ZenCache. I mention that – but the problem persists when those services are disabled.

    Is there a tweak I can do to make the post featured image findable and pinable?

    Thanks, James

  13. Hi Daniel, Many thanks for the code and tutorial! It’s very nice. I am able to show all buttons but FB always show 401 unauthorized error (the server could not verify that you are authorized to access the document requested…). Any idea why?

    Thanks,
    Pamela

  14. Hi Daniel, I think the unauthorized error maybe setup related. However, once I implemented the code to my website, the responsive menu on mobile phone is not working anymore. Any idea how I can fix this or where I should look into? Many thanks!

  15. This is great, thank you very much! I followed your sharrre version and couldn’t get G+ to work even after following all the advice.. This version works great! And for my client, worth the slight performance hit 🙂 Thank you very much!

  16. Fantastic and epic tutorial broh! Thanks so much! Kisses for you hehe :^*

  17. Great Work man. I really like your solution. I have an issue though after a few days of using them. I get Array ( [error_code] => 4 [error_msg] => Application request limit reached (4) [request_args] => Array ( [0] => Array ( [key] => method [value] => fql.query ) [1] => Array ( [key] => format [value] => json ) [2] => Array ( [key] => query [value] => SELECT url, total_count FROM link_stat WHERE url = ‚example.com/linkofarticle‘. Can you give me a hand?

  18. twitter count is not working 🙁

  19. Tuirenn Hurstfield

    6. März 2016 — 00:34

    How did you change the G+ logo?

  20. Oğuz Veli Yavaş

    25. April 2016 — 15:18

    Thanks for great article! That really help me 🙂 How we can add total share count to the left of share section?

Schreibe einen Kommentar