12-05-2010
When I was making my site I wanted to be able to have short urls to post to Twitter, etc. without having to deal with the hassle of buying another domain name. There are quite a few ways of doing this but I ended up taking the /template_group/entry_id
approach because it’s easy and sexy.
The first thing I did was setup a new template group. For example sake, I’m going to name this template group 'b' (short for blog). I’m also going to pretend our actual blog posts are located at /blog
Once you’ve made the new template group, 'b', open up the index file and paste the following code in there:
{preload_replace:my_channel="blog"}
{if segment_2 == ''}{redirect="{my_channel}"}{/if}
{exp:channel:entries
disable="categories|custom_fields|member_data|pagination"
entry_id="{segment_2}"
channel="{my_channel}"
}
{redirect="{my_channel}/{url_title}"}
{/exp:channel:entries}
This is pretty simple stuff. First we make a variable called 'my_channel' that points to our blog channel (it’s all about the reusable code people, use preload_replace like it’s your job). Then, we make sure we have a segment_2
, if not, we redirect to the main blog page. Lastly, we use an ExpressionEngine Channel loop based off of the entry_id (which is pulled from segment_2) and redirect to its "long url", /blog/url_title
To show your short url on your actual entry pages, just throw something like the following in the blog entries template (inside the channel loop):
<p>Short URL: <a href="{site_url}/b/{entry_id}">{site_url}/b/{entry_id}/</a></p>
Tada - now you’ve got yourself a really simple branded short url, none of that bit.ly stuff.