How to add a tweet this button with auto TinyURL or Bit.ly shortening

Please wait

wordpress tips tricks

How to add a Tweet This button to your wordpress posts without using any plugin or widget? Well there are few sites allow you to do that. But for instance I want the control to be in my hand and it’s pretty much no point of using a plugin or widget to do this kind of job. Why? because each time a plugin/widget loads, it takes away cpu and ram resources from server. So let me show you a nifty simple way to add a cool Tweet This button to your wordpress posts including automatic creation of TinyURL/Bit.ly url for your post. The automatic TinyURL creation for wordpress post already published at WPRecipes website but it was not implemented in their Tweet This post options. Additionally I’ve added Bit.ly API usage code by my own. Bit.ly dynamic creation of urls offers statistics and usage information (free registered account). Let me show you the implementation of that in a more useful manner.

First of all in your wordpress theme directory you should have a functions.php file which contains common functions to be used inside your themes. In case you don’t have one, create a file called functions.php inside your favorite wordpress theme directory. Now open the functions.php file and add this function which will allow you to create TinyURL.com urls on demand.

Code to generate tinyurl inside your themes functions.php:

1
2
3
4
5
// Ondemand function to generate tinyurl
function getTinyUrl($url) {  
     $tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$url);  
     return $tinyurl;  
}

or you can add bit.ly JSON API to create dynamic bit.ly urls on the fly. Bit.ly offers tracking features for the urls generated. This is a little bit more tricky (Note: this requires an user account at http://bit.ly and a API key, Once you login to your Bit.ly account you can find it here). The sample code below (don’t forget to change the login name and api key)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Ondemand function to generate dynamic bit.ly urls
function getBitlyUrl($url) {  
    // fill up this 2 lines below with your login and api key
    $bitlylogin = 'yourlogin';
    $bitlyapikey= 'yourapikey';
   
   
    // you dont need to change below this line
    $bitlyurl = file_get_contents("http://api.bit.ly/shorten?version=2.0.1&longUrl=".$url."&login=".$bitlylogin."&apiKey=".$bitlyapikey);  
     
    $bitlycontent = json_decode($bitlyurl,true);

    $bitlyerror = $bitlycontent["errorCode"];

    if ($bitlyerror == 0){
        $bitlyurl = $bitlycontent["results"][$url]["shortUrl"];
    }
    else $bitlyurl = $url;

    return $bitlyurl;
}

Ok once you are done with the code, save and close the functions.php file and open your single.php file which is your wordpress single post view template. Now you can add the piece of code underneath the function called the_content(). Add this sample code underneath there to generate an image with the link to post to twitter and additionally append the post title and post tinyurl along with it. See below.. here is the sample of a single.php file.

1
2
3
4
5
6
7
8
9
10
11
<!-- looking for the_content() -->
<?php the_content(); ?>

<div class="SocialIcons">
<!-- Note Below -->
<a target="_blank" title="Share this article with your Twitter followers" href="http://twitter.com/home?status=Reading%3A+<?php the_title(); ?> - <?php  
 $turl = getTinyUrl(get_permalink($post->ID));
 echo $turl;
 ?> (via @ruhanirabin)" rel="nofollow" class="social-bookmark"><img alt="Tweet this!" src="<?php bloginfo('template_directory'); ?>/twitter.png"/></a>

</div>

Note that the above code must have the proper image file (twitter.png file in your theme directory) to display it properly. Also you can switch the function names to getTinyUrl to getBitlyUrl.

Now this is how it looks like when you click on the button and it opens twitter to post the status entry. The entire line is generated from the button itself including the tinyurl link.

Now this is how it looks like when you click on the button and it opens twitter to post the status entry. The entire line is generated from the button itself including the tinyurl link.

As you can see above that you don’t really need any 3rd party widget or plugin to accomplish the Job because it’s pretty fast to do and you are in control of the look and feel, not to mention you can save your resources. For a live example you can use the Twitter icon from my Social media icons bar.

Alternative Reading

There is another good post about this at labnol.org. It’s the javascript based chiklet implementation of this similar topic.

About Ruhani Rabin

Ruhani Rabin is the original owner and author of this blog. He also reviews web 2.0 startups at Tech2all.com. Largely interested in web 2.0 apps & Social Media. Currently the Vice President of MOL Access Portal (MOL is owner of Friendster.com). Also he is Web 2.0 & Social Media Researcher and a Total fun Geek!.. There you have it ;)

Facebook Comments

  • Pingback: Liste de plugins, Astuces et Thèmes | 4h18

  • Pingback: Ich zwitschere – also bin ich ? - Spoony's Bike Blog

  • http://ScottsdaleWebStudio.com Dacoder

    Excellent code piece. I agree on the use of widgets, some of them are necessary but to use one for each piece of social buttons is crazy. Now that google is taking into consideration page load speed we have to remember that some of the social widgets take a http request (or more) and that adds to the time spent loading. Thanks again.

  • http://twitter.com/RositaCortez Rosita Cortez

    I have been looking everywhere for this code. Thanks so much for taking the time to write this post. I have bookmarked your website. Thanks again. It works great!

  • Pingback: Liste de plugins, Astuces et Thèmes - Debuter avec Wordpress

  • Pingback: wp-popular.com » Blog Archive » How to add a Tweet This button with automatic Bit.ly/TinyURL creation for wordpress post without any 3rd party plugin or widget

  • Pingback: How to Add Tweet Text with Tinyurl in WordPress Posts

  • http://www.ilithya.net ilithya

    Thanks a lot! It was a great help for my share in twitter button =)

  • http://www.alexsolerjover.com Alex Soler

    Thanks a lot for this trick! I just added it to my blog and works perfectly.

  • http://greensmoothie.com/ Val Archer

    let me try again – as + and as #43

  • http://www.greensmoothie.com/ Val Archer

    Hi Yaniv – I'm trying to send + to twitter via bit.ly. I tried it all ways, as + and as +, with your 2-line replacement and without, and it always shows up as blank space on twitter.

    Does anyone perhaps know how to get a + sign in the title, to display at twitter?

  • http://twitter.com/Trindaz Dave Trindall

    There's also a service that does a Tweet This button with automatic URL shortening at http://ko.ly (no php coding required)!

  • http://daveingram.ca/ Dave

    Thanks for this – I was looking for a non-plugin alternative to TweetMeme and this fits the bill perfectly. Nice and light.

    I did find that I had to remove the headupmark tags in order for it to work properly but just now looking at the code above noticed that there is a “;” after the “<” bracket that follows the “status=” section of the code. Is that what was messing it up? Do you need to use these tags? The code seems to work without them.

    Dave

  • http://yaniv.golan.name Yaniv Golan

    Quick fix – the code breaks when the URL contains Unicode characters.

    To fix that, use your favorite Unicode-compatible URL encoding function before sending the URL to bit.ly, and when parsing the response, replace:

    $bitlyurl = $bitlycontent["results"][$url]["shortUrl"];

    with:

    $temp = array_values($bitlycontent["results"]);
    $bitlyurl = $temp[0]["shortUrl"];

    This removes the dependency on both bit.ly and you encoding the URL the same way.

  • Ori

    Thank you so much for this! It did exactly what I needed and nothing more, and gave me the control I wanted. Excellent.

  • http://abouthere.co.uk/blog Rob

    I tried your code a number of times on my site, in order to replace the current “Tweet this” link already in my theme.

    Unfortunately, despite my effort, it never worked. And the page stopped loading once it got to that part of the code. I had the relevant addition to my theme functions.php and here's what I was editing into the single.php

    <a target=”_blank” title=”Tweet this” href=”http://twitter.com/home?status=Reading%3A+<?php the_title(); ?> – <?php $turl = getTinyUrl(get_permalink($post->ID)); echo $turl; ?> (via @jamesbrobinson)” rel=”nofollow” class=”social-bookmark”><img src=”<?php bloginfo('template_directory'); ?>/images/social-twitter.gif”alt=”Tweet this!”>

    What have I missed please?

  • http://insurances-loans.com/ aks

    thank u for sharing. this one the interesting article which i read related to short url website. thanks again for this.

  • http://insurances-loans.com/ aks

    thank u for sharing. this one the interesting article which i read related to short url website. thanks again for this.

  • http://www.ruhanirabin.com Ruhani Rabin

    yes using javascript snippets

  • http://www.ruhanirabin.com Ruhani Rabin

    Look for index.php file and apply the code similar as described above.

  • Leslie

    Any guidance on how to add in the 2nd tranche of this code when using the Atahualpa theme with no single.php file? Thanks.

  • Leslie

    Can you give any guidance for how to add the 2nd tranche of code when using the Atahualpa theme which has no single.php file?

  • http://www.sagive.co.il/ sagive

    aint there a way to add that to a regular html website ?

  • http://twitter.com/jamesjfoley James Foley

    Hi Ruhani,

    This is exactly what I'm looking for, but need this to work in Blogger. Any ideas how to achieve this without php ?
    Thanks

    james

  • Ferrel

    Thank you for putting it together. There are a lot of pre-made packages out there that are impossible to edit. I also like to do things my way to ensure they match my site.

    Your code was easy to use, easy to edit and did exactly what I wanted. I really appreciate it!

  • Juhill117

    Too complicated. There must be an easier way of adding the bit.ly or tinyurl to a tweet. There must be! Too any folks are using it! Thanks anyway.

  • http://www.spyblogger.com SpyBlogger

    Thanks for the help, good explanation!

  • http://twitter.com/PennyGo Penny Go

    Thanks – I'll practice this next time I start a new site, before I load content… (Ok, call me just a little timid!)

  • http://twitter.com/PennyGo Penny Go

    Thanks – I'll practice this next time I start a new site, before I load content… (Ok, call me just a little timid!)

  • http://www.ruhanirabin.com Ruhani Rabin

    Hi kelly,

    Thanks for posting this up :) Actually I went to your blog and tried to tweet a post and it worked fine. Are you using a protected account or something. Or your ISP filters the parameter calls.. ? or your twitter account has any problems.. give u an idea.. why not create a new twitter account and test is out…

    Also many thanks for the notification about the contact form :) it's working now :)

    Please let me know what is the outcome..

  • http://www.empowermentsanctuary.com/innersanctum/ Kelly

    Hi There,

    Thanks for posting the instructions for how to use a Tweet This button without having to use another infernal plugin!!

    QUESTION: Every time I click the button, I am taken to the Twitter Whale. EVERY time. Yet, when I go directly to Twitter, I\'m able to log in, post, RT, etc without any issues.

    I\'ve even tried it in the middle of the night when Twitter usage is relatively low, but I get the same results.

    Do you know what could be causing this?

    PS..the captcha functionality on your contact form is broken – no image displays, yet a captcha code is still required.

  • http://to.ly Jonas Lejon

    Using to.ly as a url shrinker is also easy, check http://to.ly/api_info.php

  • http://www.ruhanirabin.com Ruhani Rabin

    i am trying to find out but it doesn't hang on my server. what php version r u using? Also the script shouldn't hang because I have a error checking.

  • http://www.eclecticelectronics.net blued888

    Somehow the script hangs when I use it. How do I find out what I'm doing wrong?

  • http://dustyreagan.com Dusty

    This was super helpful! Thanks so much for the bit.ly php function!