How To Make Automatic Tr.im Links In WordPress Posts

Posted in Tutorials, Wordpress | On 1st February 2010 | 4 Comments


Today I’m going to show you how to automatically add a tr.im link for each post on your WordPress install using a little PHP, CSS and the tr.im API.

I was recently working on a project for a client when they required this function, to cut a long story short they changed the design specification and ended up not needing this option.

Its really a straightforward tutorial, you will need to edit functions.php (or whatever your theme functions file is called), single.php (single post page) and your stylesheet, also one file must be uploaded via FTP.

Before you begin REMEMBER to backup your files! Once you have finished editing your files please save.

Theme Functions (functions.php)

Place the following somewhere below the “<? php” code at the top of the file:
[sourcecode language="text"]function gettrim($url) {
$trim= file_get_contents(“http://api.tr.im/v1/trim_simple?url=”.$url);
return $trim;
}[/sourcecode]
This accesses the tr.im API and tells it to shorten any URL you specify with a $url variable.

Single Post (single.php)

Add the following code within your single.php file, somewhere after <? php the_content(); ?> should work well.

[sourcecode language="text"]

ID)); echo ‘Tr.im Link: ‘.$trimmed.’‘?>

[/sourcecode]

This displays your shortened URL with a link, description and tr.im icon.

The Icon

You can get that here: http://www.webm.ag/tuts/icon.jpg (right click and save) you must then upload this icon image via FTP to your blog’s images directory, in my example above I have used /img/ so please alter the directory name in single.php to suit.

Stylesheet

Add the following code anywhere in your stylesheet.
[sourcecode language="text"].trim {margin: 10px 0 10px 0;}
.trimicon {float: left; border:0; width: 20px; height: 20px;}
.trimed {float: left; margin: 0 0 0 10px; font-weight: bold;}
.clearer {clear:both;}[/sourcecode]
This gives the divs from the single.php their values, such as margin, border and alignment etc… this can be altered and modified to fit in with your design.

Once you visit a single post on your blog you should now have a tr.im link to offer your readers so they can quickly share on forums, blogs or social media outlets.

McBonio is a full time web designer, blogger and general web lurker. He runs Tropica Web Design, which is a web agency based in Liverpool, UK. You can also catch McBonio at Twitter: @mcbonio

Visit McBonio's website

4 Comments