Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
Web Dev + WordPress + Security

Stupid Twitter Tricks

[ Twitter ] Might as well face it, Twitter is here to stay. Not that it’s all that bad, just used to be a lot more laid-back and enjoyable. These days it seems to have been taken over by the lowest common-denominator, mostly high-school twits or useless commercial propaganda. Even so, I still enjoy tweeting the occasional profound thought once in awhile, and even like to play around with various types of “advanced” Twitter functionality. You know, cool stuff like including “Tweet This!” links with short URLs, showing off my number of Twitter followers, displaying the number of tweets for each post, and even backing up my marvelous tweets quickly and easily. As you might have guessed, these are the kind of stupid Twitter tricks that you will find in this article. So kick back, relax, and enjoy these twitterific techniques that will make you go.. tweet.

“Tweet This!” short links for posts

I like to include an easy way for readers to “tweet” my posts, but the URLs are generally way over Twitter’s 140-character limit. Fortunately, we can use PHP’s handy file_get_contents function to grab short versions of our URLs from a free minifying service like TinyURL.

All we need to do is add the following script to your web pages or your functions.php file:

function shortenURL($longURL) {
	$shortURL = file_get_contents("http://tinyurl.com/api-create.php?url=".$longURL);
	echo $shortURL;
}

Then, in the location where you would like to display your shortened “Tweet This!” links (e.g., after your post loop), call the function and create the link with the following code:

<a href="http://twitter.com/home?status=Reading:%20<?php the_title(); ?>:%20<?php shortenURL(get_permalink()); ?>" rel="nofollow">Tweet This!</a>

This is basically a link using the Twitter API to specify the contents of our tweet. For each post, the value of the_title() and get_permalink() will change to reflect its title and URL, respectively. If you are using a platform other than WordPress, you will need to use the equivalent of these dynamic tags.

Once you have this code in place, it will generate “Tweet This!” links that send the following information to Twitter (using this post as an example):

[ Reading: Stupid Twitter Tricks: http://tinyurl.com/yhz5ok3 ]

As you can see, the original long URL for this post was automatically shortened via the TinyURL service. Nice, clean and effective.

For more social media links, check out my comprehensive article, Fully Valid, SEO-Friendly Social Media Links for WordPress.

Custom short links using your own domain name

If you would rather not rely on a shortening service (such as TinyURL) for your shortened links, fret not — it is easy to create your own, customized URLs. There are several good reasons why you might prefer to use your own domain for your shortened URLs, including:

  • preservation of valuable link juice
  • prevention of link loss if the shortening service dies
  • control over the appearance and branding of your links

The key to setting up customized shortened “Tweet This!” links is the inherent post ID that is associated with each of your posts. Regardless of whether or not you have permalinks setup, every one of your posts has its own unique post ID, such as seen in these examples:

We can use these post IDs to fashion our own shortened URLs, and then use those shortened URLs to create our own customized “Tweet This!” links. All we need is touch of HTAccess placed in the same .htaccess file as our WordPress permalinks:

RewriteRule ^x/([0-9]+)$ http://domain.tld/?p=$1 [R=301,L]

This directive will redirect our custom shortened URLs to our default WordPress URLs, which WordPress will then redirect according to any existing permalink rules. Once this technique has been implemented, the following redirects will take place for each of your custom URLs:

[ Diagram showing the flow of redirects used in this technique ]

Once we have the HTAccess code in place, we use the same basic markup as in our previous example to create the link. Add the following code to the desired location in your theme file (e.g., after the post loop):

<a href="http://twitter.com/home?status=Reading:%20<?php the_title(); ?>:%20<?php echo get_option('home'); ?>/x/<?php the_ID(); ?>" rel="nofollow">Tweet This!</a>

This code will create “Tweet This!” links that send the following information to Twitter (using this post as an example):

[ Reading: Stupid Twitter Tricks: https://perishablepress.com/x/719 ]

As you can see, the original long URL for this post is now a customized short URL using the same domain. Feel free to change the “x” to whatever you want — just remember to edit both the markup link and the .htaccess directive if you decide to do so.

I should also note that, for any of these “shortened” URL examples, we are only using Twitter as an example application. Many sites these days simply include a shortened version of the post URL for people to copy & paste anywhere they wish. To do something similar with the current technique, we would simply include the following snippet:

<?php echo get_option('home'); ?>/x/<?php the_ID(); ?>

Drop-dead simple short URLs using the post ID

For the sake of completeness, keep in mind that we can use the post ID to (re)create our original WordPress URL structure:

http://domain.tld/?p=719

That’s pretty short, and may work perfectly for your short links if the format is suitable for you. All we would need to do is include the following code into your WordPress theme:

<?php echo get_bloginfo('url')."/?p=".$post->ID; ?>

WordPress will automatically redirect such URLs to the corresponding permalink (if you have permalinks enabled).

Display the number of your Twitter followers in plain text via JavaScript

Another fun thing to do with Twitter is show off your subscriber number on your website. Many sites these days prominently display two numbers: one for their Feedburner subscriber count and another for their Twitter follower count. Displaying either count with a button or badge is a no-brainer, but displaying the numbers in plain text allows for greater stylistic control. Plain text is desirable because you can do just about anything with it, whereas a badge just kind of sits there, looking ugly.

To get our Twitter follower count in plain text, we need to include some free JavaScript made available to us at TwitterCounter. Just place this code wherever you would like to display your follower count:

<script type="text/javascript" language="javascript" src="http://twittercounter.com/widget/index.php?username=username"></script>

Simply edit the “username” to match your own and you are off to the races.

Display the number of your Twitter followers in plain text via PHP

If you would rather not rely on JavaScript and a third-party service to deliver your follower count data, we can use PHP’s excellent curl() functionality (edit the “www.domain.tld” to match your own):

function curl($url) {
	$ch = curl_init($url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch,CURLOPT_HEADER, 0); 
	curl_setopt($ch,CURLOPT_USERAGENT,"www.domain.tld");
	curl_setopt($ch,CURLOPT_TIMEOUT,10); 
	$data = curl_exec($ch);
	curl_close($ch);
	return $data;
}

That curl snippet will grab the content of the input URL and prepare it for parsing via the following code:

function followerCount($username) {
	$followers = curl("http://twitter.com/statuses/user_timeline/".$username.".xml?count=1");
	$xml = new SimpleXmlElement($followers, LIBXML_NOCDATA);
	return = $xml->status->user->followers_count;
}
echo followerCount("username");

This second snippet uses SimpleXML to parse the curl output via the Twitter API. SimpleXML is pretty common on most servers running at least PHP 5. The only thing you need to edit is the “username” in the last line. Everything else is roses. Drop this code into a web page and enjoy your follower count displayed anywhere you like, and in plain-text, no less.

Display the number of tweets for each page or post

If you are running SimpleXML (you probably are, ask your host), displaying the total number of tweets for any given post or page is easily accomplished with the following slice of PHP:

function tweetCount($url) {
	$content = file_get_contents("http://api.tweetmeme.com/url_info?url=".$url);
	$element = new SimpleXmlElement($content);
	$tweets = $element->story->url_count;
 	echo $tweets . " tweets!";
}

If you are using WordPress, you may place that code into your active theme’s functions.php file. Then, to display the total number of tweets for your posts, you would add the following function call to your post loop:

<?php tweetCount($post->permalink); ?>

You can also show the number of tweets for a particular page, even if it is not on your site. For example:

<?php tweetCount("http://perishable.biz"); ?>

Backup your tweets

Once you have been tweeting for awhile, you may begin to wonder what would happen if Twitter ever lost all of your tweets. It could happen, and if it does, do your tweets contain anything of value? If they do, I would highly recommend making regular backups (like monthly or something) of all your tweets. Doing so is easy. All you need to do is login to your Twitter account and enter the following URL into your browser:

http://twitter.com/statuses/user_timeline/username.xml?count=n

Before this will work, you need to replace the “username” with your actual username, and also change the “n” with the number of tweets you would like to download. To download all of your tweets, check your number of updates on your Twitter profile page. After entering this URL into your browser, you will be taken to an XML page containing your tweets. To make a backup, just save that page to a safe location on your computer.

Now you can rest so easy just knowing deep down that all your precious tweets are safe and sound ;)

About the Author
Jeff Starr = Fullstack Developer. Book Author. Teacher. Human Being.
USP Pro: Unlimited front-end forms for user-submitted posts and more.

15 responses to “Stupid Twitter Tricks”

  1. Awesome :) I had a problem with the ‘twit this’ link, since I wanted to call it in my header and had to declare global $post to get $post-ID to work.

    Mind, if you have quotes in your titles, this breaks. I’ve yet to sort out a way around that with trim().

  2. Aaand I got my own answer:

    <?php if (is_single()) { global $post; $post->ID; ?><p class="entry-meta"><a href="http://twitter.com/home?status=Reading:%20<?php echo str_replace('"','',get_the_title()); ? rel="nofollow" rel="nofollow ugc" rel="nofollow ugc">:%20<?php echo get_bloginfo('url')."/?p=".$post->ID; ?>" rel="nofollow">Tweet This</a></p><?php } ?>

    This goes in my header and works happily :)

  3. Jeff Starr 2009/10/18 3:08 pm

    You beat me to the punch, Ipstenu :)

    Another thing that works great for encoding URLs is PHP’s urlencode, as used in my article on Fully Valid, SEO-Friendly Social Media Links for WordPress.

    I use urlencode to clean up all of the query-string characters in the social media links.

  4. Wow, that’s a hefty amount of twitter tricks… I’m gonna use a few myself if ya don’t mind :)

  5. Delighted 2009/10/19 5:58 pm

    This is not stupid at all.. I am a newbie with php and this definitely helps.. thank you!

  6. Jeff Starr 2009/10/20 8:31 am

    @Fedor, @Delighted: Thanks for the feedback :)

  7. Max Weaver 2009/10/21 11:59 pm

    I was really interested in the method of backing up my tweets, but the method you suggested just creates a garbled mess! To prune your tweets out of this would surely drive you mad in no time.

    Gina Trapani has another method that doesn’t add all the guff that this method does but it is a bit more complicated.

  8. Jeff Starr 2009/10/22 6:42 am

    Hi Max, It’s a little more useful than a “garbled mess,” actually. The results are returned in XML format, which is quite logical and organized. The contents may look strange in a browser, but add that content to a XML/RSS parser or even a feed reader and watch the magic happen. And, the best part about having your tweets backed up in XML format is that it makes importing a breeze.

  9. Max Weaver 2009/10/22 7:03 pm

    Oh right. Thanks for that tip Jeff. I’ll find an RSS reader and try importing them then.

  10. clippingimages 2009/11/01 3:55 am

    Some thing new to learn. Thanks for sharing this post. Very informative.

  11. Jeff Ivany 2010/03/09 8:16 am

    Doh. I thought I had this working but it seems I’ve broken something along the way. I’m basically using the same as what you have above but for some reason, after following domain.tld/x/555 I get my browser showing domain.tld/?p=555 in the URL bar but it’s displaying the home page (ie not actually redirecting to the post). Any ideas? I’ll keep poking at it with this stick and see if I can make it roll over and play nice. :(

  12. Jeff, not sure.. there are quite a few variables at play here, including the htaccess, the template code, and any plugins or functions that might be affecting things. Let us know if you discover a solution!

Comments are closed for this post. Something to add? Let me know.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
The Tao of WordPress: Master the art of WordPress.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.