Try Tuts+ Premium, Get Cash Back!
Using Bitly URLs in WordPress and use them with Twitter and GooglePlus Scripts

Using Bitly URLs in WordPress and use them with Twitter and GooglePlus Scripts

Tutorial Details
  • Program: WordPress
  • Difficulty:Intermediate
  • Estimated Completion Time:30 Minutes
  • Files required to edit : functions.php and single.php (make a backup of these files. Just in case!)

So you want to use your bitly account with your WordPress based website? Well that’s really simple. All you need is to pay attention and follow the steps accordingly in the following tutorial!

When bitly was introduced most of the developers and users were not comfortable using it. Later on as the World Wide Web developed more, sites like Twitter, Facebook and YouTube started to use the same concept. Now Google Plus even supports it.

In this article you will be learning an easy and useful method of adeptly connecting your bitly account with your WordPress website or blog, and then use your bitly account to generate short urls for “Tweet” and “Share” buttons. This task is really simple and I use it on my blog as well and the results are quite impressive. Best of luck trying it out and if you face any problem, do leave your questions in the comments section below.


Step 1 Preparing The Code

Login to your bitly account. If you don’t have one, it takes only a minute to setup your account. After logging into your account, go to the settings page, scroll down almost half the way and copy your API. We’ll be using this in a minute or so.


Step 2.1 Modifying Your functions.php

Copy the code below and paste it in your functions file. (Although the code is straightforward, I have added comments in the code so as to make it easier to understand).


//automatically create bit.ly url for wordpress widgets
function bitly()
{
	//login information
	$url = get_permalink();  //for wordpress permalink
	$login = 'USERNAME-HERE';	//your bit.ly login
	$apikey = 'API-HERE'; //add your bit.ly API
	$format = 'json';	//choose between json or xml
	$version = '2.0.1';
	//generate the URL
	$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$apikey.'&format='.$format;

	//fetch url
	$response = file_get_contents($bitly);
//for json formating
	if(strtolower($format) == 'json')
	{
		$json = @json_decode($response,true);
		echo $json['results'][$url]['shortUrl'];
	}
	else //for xml formatting
	{
		$xml = simplexml_load_string($response);
		echo 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
	}
}

Step 2.2 Writing a Test post

Now, enter your username and paste your API in the place given. Upload your functions.php file in your theme folder. Now write a test post in html mode and paste this

<?php bitly(); ?> 

in the content region. Go to the published post and see whether the link is bitly redirected URL or not. If not then check your username and bitly API in the functions file again.


Step 3 Adding Twitter and +1 buttons

Now you are familiar with the code and how to use this, let’s benefit from the code and see some examples for inspiration and encouragement. Below are examples of this code being used with Twitter and Google Plus that I use on my blog.

The first one is of twitter and the code shows the size of the button and the links to suggested people.


<a href="http://twitter.com/share?url=<?php echo urlencode( bitly()); ?>&counturl=<?php urlencode(the_permalink()); ?>" class="twitter-share-button" data-count="horizontal" data-via="USERNAME-HERE">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>

You can copy the above code or you can go to Twitter and design the code as you like. Remember to change the “data-via” type. Notice the urlencode function is passed the newly created bitly function.

For Google Plus, copy the code below. If you want a more customized code, then go to Google+ and design the +1 button as per your liking. Notice how I have changed the code to incorporate bitly function.


<g:plusone size="medium" href="<? bitly(); ?>"></g:plusone>

Step 4 Usage

Now that you have edited and customized the codes, paste the edited code in the loop of your wordpress file or you can also paste it in single.php right after the meta() tag.

Now when you’ll click on the Tweet or +1 button, you will get the bitly URL. Happy Tweeting!


Conclusion

So what is the use of these bitly urls?

  • First, you can easily monitor the your bitly links from your bitly account. It displays the number of times your link was visited.
  • Second, the shortened URL can easily be tweeted and +1 by your followers and readers alike.
  • Third you can easily send the shortened links to your friends and others via SMS and email. These shortened urls look elegant and do not clutter the place in emails and you can easily send these to corporate and the like.
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.welancers.com Aslam Doctor

    Awsome. I just configured it with “AddThis” button :P

  • http://www.jvsoftware.com Javier Villanueva

    Nice, why you don’t use wp_remote_get() instead of file_get_contents() though?

    • Bilal Shaheen
      Author

      Sure Javier, you can use the wp_remote_get() functionality for fetching external links. Choose whatever you like as both the functions perform the same job :)

  • Pingback: A Free wordpress newsletter » WordPress News, Tutorials & Resources Roundup No.11

  • Pingback: Using Bitly URLs in WordPress and use them with Twitter and GooglePlus Scripts | Shadowtek | Hosting and Design Solutions

  • Pingback: Как использовать Bitly для сокращения ссылок в WordPress | Wordpresso

  • Pingback: WordPress News, Tutorials & Resources Roundup No.11

  • http://matiasmancini.com.ar Matias Mancini

    Great Start,
    I digg a little and realize that every time the post loads must run the query to the bitly servers, so i updated the function to save a custom field with the bitly url before.

    if( !function_exists('bitly') ){
        
        // Display bitly custom field, if nox exists creates it
        function bitly($post_id){
    
            if( !get_post_meta($post_id, '_bitly', true) ){
                $shorten = get_bitly();
                add_post_meta($post_id, '_bitly', $shorten);
                return 'NEW ' . $shorten;
            }else{
                return 'EXISTING ' . get_post_meta($post_id, '_bitly', true);
            }
        }
    
        // generate bitly short url with bitly API, only call this if no custom field is setting
        function get_bitly(){
            //login information
            $url = get_permalink();  //for wordpress permalink
            $encodedUrl = urlencode($url);
            $login = 'o_2gjngkcukf';   //your bit.ly login
            $apikey = 'R_d424558755617553c89a492a8ef81482'; //add your bit.ly API
            $format = 'json';   //choose between json or xml
            $version = '2.0.1';
    
            //generate the URL
            $bitly = "http://api.bit.ly/shorten?version=2.0.1&longUrl=$encodedUrl&login=$login&apiKey=$apikey&format=$format";
    
            //fetch url
            $response = wp_remote_get($bitly);
    
            //for json formating
            if(strtolower($format) == 'json')
            {
                $json = @json_decode($response['body'], true);
                return $json['results'][$url]['shortUrl'];
            }
            else //for xml formatting
            {
                $xml = simplexml_load_string($response['body']);
                return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
            }
        }
    }
    
    • http://BureauofTrade Max

      Matias! You’re a lifesaver. Just as an FYI, if you’re running a high-traffic blog — the script in this tutorial can push you over your API limit super-quickly (this happened in less than 24 hours for us), much better to cache the links per Matias’ suggestion.

      -Max

  • Pingback: Quick Tip: Writing Simple Modular Code | Wptuts+

  • Pingback: Quick Tip: Writing Simple Modular Code | Wordpress Webdesigner

  • Pingback: My Stream | Quick Tip: Writing Simple Modular Code | My Stream

  • Pingback: Quick Tip: Writing Simple Modular Code | Shadowtek | Hosting and Design Solutions

  • Pingback: Quick Tip: Writing Simple Modular Code | How to Web

  • blender

    Thanks for the suggestion Matias, but copy and pasting your code into functions I get a T-string error on line 8, which I believe is

    return ‘NEW ‘ . $shorten;

    Is there a typo in there somewhere or do I need to alter more than my bitly login and api?

    Thanks!

    • http://wp.envato.com/ Japh Thomson
      Staff

      Hello Blender! Looks like the error may actually be on the previous line?

      • blender

        Thanks Japh, but I’m not seeing it (my newbie coder status is showing). Something wrong with add_post_meta?

        • Liz

          I’m also seeing the same issues. Any chance there is a solution for this? I’m new enough to PHP I can’t tell what’s causing the issue.

          • Liz

            I actually found the issue, copying and pasting into the text editor from here changed the format (character type) of the ‘ ‘ … which leads to errors. Replacing those manually fixed the problems!

            Thanks!!

          • http://wp.envato.com/ Japh Thomson
            Staff

            Thanks, Liz for reporting back on this! I’ve updated the code snippet in Matias’ comment to use our formatting, so hopefully that rectifies the issue for anyone else.

  • mmbee

    This is exactly what I was looking for. Thanks a bunch.

  • Liz

    Hello again! I’m having a different issue (still using Matias’ alteration of the code).

    This:

    <a href="http://twitter.com/share?url=&counturl=” class=”twitter-share-button” data-count=”none” data-via=”USER_NAME_HERE”>Tweet

    …will not display properly, and in fact hides any content that comes after this snippet!

    But when I remove this portion of the href: “” The button works (but no link of course) and the content following this tag does not disappear.

    Any suggestions for where to look for the problem?

    I thought it might be because I used $post_slug rather than $post_id in Mattias’ code, but reverting back to $post_id does not help.

    • Liz

      Whoops, I forgot to wrap the code! Trying this again:

      < a href=”http://twitter.com/share?url=&counturl=< ?php urlencode(the_permalink()); ?>” class=”twitter-share-button” data-dnt=”true” data-count=”none” data-via=”USER_NAME_HERE”>Tweet< /a>

      Breaks things. Removing this part:
      <?php echo urlencode( bitly()); ?&gt

      Fixes the disappearing content issue, but then no URL.

      • Liz

        So I found the problem with the no URL. I’m dev-ing on an a localhost with MAMP/WAMP… and twitter will not display a URL that is not valid. //local-host/… is NOT valid (no surprise) so this is a feature you wouldn’t be able to test this until you’ve got it live or have an active dev environment that gives a full URL.

        Facebook on the other hand, displays the URL but will just say that it’s not valid.

        Hope this helps someone else out in the future!

  • http://www.ladsrack.com/ Mens Underwear

    great tutorial

  • Pingback: Suchmaschinenoptimierung, Online Marketing, E-Commerce

  • http://twitter.com/parsnet4u ali smith

    <g:plusone size="medium" href="”>
    or
    <g:plusone size="medium" href="”>

    Which is better?

    Use the short URL instead of home address on Google Plus no problem in terms of seo?

    Redirection not acted to the detriment seo website?

    Thank you