Tag Archives: tweet button using tinyurl

How to Add Twitter’s Official Tweet Button in WordPress using TinyUrl

It’s very simple to just add the official tweet button to your site, but if you have very long Search engine friendly URLs (see any post URL on this site) it can be a bit difficult!

To implement the tweet button with a short URL I used tinyurl, as unlike bit.ly you don’t need to create an account and the only data it sends back to you is the shortened URL.

The code should be implemented within the loop, you can even include it if you want to keep file sizes low.

//the url you want to make tiny
$maketiny = 'http://tinyurl.com/api-create.php?url='.get_permalink();

/*Initialise and set options for cURL
(this lets you transfer data between URLs)*/
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $maketiny);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

//execute and close cURL
$data = curl_exec($ch);
curl_close($ch);

//You now have the tinyurl stored in $tinyurl
$tinyurl = $data;

Now that you have the tinyurl stored in the $tinyurl variable, you can use it in the twitter button!

You have two choices about how to code the button, either use JavaScript or an iFrame.

For JavaScript you need the following code:

<script src="http://platform.twitter.com/widgets.js"
type="text/javascript"></script>
<div>
   <a href="http://twitter.com/share" class="twitter-share-button"
      data-url="<?php echo $tinyurl; ?>"
      data-count="<?php the_permalink(); ?>">Tweet</a>
</div>

For an iFrame you need this code:

<iframe allowtransparency="true" frameborder="0" scrolling="no"
src="http://platform.twitter.com/widgets/tweet_button.html?
url=<?php echo $tinyurl; ?>&amp;counturl=<?php the_permalink(); ?>"
style="width:130px; height:50px;"></iframe>

The following attributes and query strings can be used:

Query String Attribute Description Default
url data-url URL of the page to share HTTP Referrer
via data-via Screen name of the user to attribute the Tweet to none
text data-text Default Tweet text Content of the <title> tag
related data-related Related accounts None
count data-count Count box position (can be horizontal, vertical or none) horizontal
lang data-lang The language for the Tweet Button en
counturl data-counturl The URL to which your shared URL resolves to (only needs to be used if a short url is used in for the other url) the url being shared

For more information on the tweet button see the Official Twitter Tweet Button Page.