code Tag Archive

Custom Shortlinks for WordPress

I was lucky and managed to get my hands on a neat little .co domain, djr.co, and I decided that since it is now the shortest domain that I own that I’d first put it to use for the short links on my blog, and as my own personal url shortener.

I was lucky and managed to get my hands on a neat little .co domain, djr.co, and I decided that since it is now the shortest domain that I own that I’d first put it to use for the short links on my blog, and as my own personal url shortener.

The (really) short version

  • I’ve set up Lessn to take care of the personal url shortener side of things
  • And I’m using a simple combination of a WordPress filter function and an .htaccess/index.php redirection combo to handle the shortlinks for my blog.

The long version (for those who want more info)

Personal URL shortener

For the general url shortener there a few different options floating around, but I didn’t need anything super fancy with graphs and counters and all that stuff, I just wanted something simple and easy to setup — and most importantly something that worked. So I went with Shaun Inman’s nice little Lessn script and its working great.

Summary — if you want to set up your own url shortener using your own domain, then give Lessn a go. It is dead simple to setup.

Custom WordPress ‘shortlinks’

As of version 3.0, WordPress now come with a built in function called ‘wp_get_shortlink’ which, as you can probably guess, returns a ‘shortlink’ for the relevant post/page.

By default these ‘shortlinks’ take the form of http://deanjrobinson.com/?p=1345 — which also happens to be the default post links if you don’t have pretty permalinks set up, I’ll explain why this point is important shortly.

Getting djr.co ready for redirection

The first thing I needed to do was to set up things on djr.co and make sure it was working as I expected.

I had considered using the api built into Lessn to auto generate a shortlink when I publish a post, I even found a plugin that would have done it for me pretty easily, however I rules this out for a couple of reasons:

  • It would have meant adding additional meta data fields against posts — not necessarily a bad thing, but also not really necessary for my needs
  • I would have had to either modify my templates to output the new short links, or create a filter to take care of it for me
  • And the main reason was that I wanted ‘shortlinks’ to be available for all my old posts as well — without me having to go back and generate them.

The ‘solution’ I decided on is essentially a really stripped back version of Lessn — without the need to call off to the Lessn database etc because our WP posts already have unique ids which we can use for the redirection. More specifically it just two files a .htaccess file and an index.php file.

First, the .htaccess file, this is exactly the same as the one from Lessn.

This takes the url, eg. http://djr.co/m/1345, and passes it to
http://djr.co/m/index.php?token=1345 ready for the redirection.

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond	%{REQUEST_FILENAME}	!-d
  RewriteCond	%{REQUEST_FILENAME}	!-f
  RewriteRule	(.*) index.php?token=$1	[QSA,L]
</IfModule>

You might be curious as to why I haven’t just redirected it to my primary url using the htaccess, I’ll get to that in a sec.

Second, the simple index.php

This is based on the index.php file from Lessn, but cut down to just what I needed for my blog redirection. That means no need to call any of the Lessn includes, or make any database queries, just grab the id and redirect it off to my blog.

If no ‘token’ is passed though the page will simply return a 404. The two reasons for using this index.php file to handle the actual redirect are so that I can clean up the token (using strip_tags) just in case someone tries something nasty, and so that I can check that the token is numeric (using is_numeric) — this is because WordPress post/page IDs are only numeric, so any other values obviously aren’t going to work anyway.

This is what the cut-down, modified index.php file looks like. You’ll notice that the url format for the ‘Header Location’ matches the default WordPress ‘shortlink’ format I mentioned above. This is because no matter how you have your pretty permalinks set up, these default links will always work.

<?php

if (!empty($_GET['token'])) {
  $id = strip_tags($_GET['token']);
  if(is_numeric($id)) {
    header($_SERVER['SERVER_PROTOCOL'].' 301 Moved Permanently');
    header('Location:http://deanjrobinson.com/?p='.$id);
    exit();
  }
}

header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
header('Status:404');
die('404 Not Found');

?>

Getting WordPress to use these custom shortlinks

To get this working, all I needed to do was add a really simple ‘filter’ to the functions.php file in my current theme.

I’m using a filter so that I can continue to use the built-in ‘wp_get_shortlink’ function that is available in WordPress (since 3.0). This function can be used something like this:

<a href="<?php echo wp_get_shortlink(); ?>" title="ShortURL for this post">Short URL</a>

By running the filter over the standard function not only do I not have to update any of my theme templates, I will also be able to retrieve my custom short url by using the “Get Shortlink” button that has been added to the create/edit post screen in the WordPress admin, just below the post title.

<?php

function my_custom_shortlink_filter() {
  global $post;
  return 'http://djr.co/m/'.$post->ID;
}
add_filter('get_shortlink','my_custom_shortlink_filter');

?>

Best of all, because the shortlinks are based on the unique post ids (which every post has) the shortlinks will instantly work for all my posts going right back to the beginning of this blog without me needing to change anything else. Yay.

Article 23 Jul 2010 1 comment
·•·

Enabling Twitter avatars within BuddyPress

First up, the first step in this process is to install the Twit Connect plugin which you can do by following these instructions, then you can proceed with enabling Twitter avatars.

First up, the first step in this process is to install the Twit Connect plugin which you can do by following these instructions, then you can proceed with enabling Twitter avatars.

This is just a quick filter that I wrote while I was setting up help.deanjrobinson.com last week after I discovered that the twitter avatars weren’t working because of a different function/filter being used by BuddyPress.

I make no claims that this additional function is perfect, but I haven’t come across any problems with it yet, and I only knocked it together quickly. If you find anything wrong with it, or have any suggestions as to how it could be improved/simplified please let me know.

This new function based on one of the original functions that comes with the Twit Connect plugin which enables twitter avatars on regular WordPress blogs, just a with a few tweaks.

What you need to do is add the following code to the functions.php in your current BuddyPress theme. You can download a plain text copy of this function here (it’ll probably more reliable than copy-and-pasting from this page). Remember to backup your functions.php file before making any changes… just in case.

UPDATE: Appears some people who added this function the functions.php file in the default BuddyPress theme were seeing some error messages (I have not yet been able to recreate this error, but more than one user has reported it). Ideally you shouldn’t be modifying the default BP theme directly, you should be doing it via a child theme (find out how), so this code should be then added to the functions.php in your child theme.

7th March, UPDATE I’ve updated the function below (and the downloadable version above) to use http://tweetimag.es for the static twitter avatar URLs, it looks like it might a more reliable/consistent service.

<?php

 function bp_twc_get_avatar($avatar, $id_or_email='') {
  global $comment, $twc_user_login_suffix;

  if(is_object($comment)) {
   $user_id = $comment->user_id;
  }

  if (is_object($id_or_email)) {
   $user_id = $id_or_email->user_id;
  }

  if (is_array($id_or_email)) {
   if ($id_or_email['object']=='user') {
    $user_id = $id_or_email['item_id'];
   }
  }

  if (get_usermeta($user_id, 'twcid')) {
   $user_info = get_userdata($user_id);
   $twav_suffix = '';

   if ( $id_or_email['width'] ) {
    $twav_size = $id_or_email['width'];
    if( $twav_size < 32 ) {
     $twav_suffix = 'm';
    } else if ( $twav_suffix < 64 ) {
     $twav_suffix = 'n';
    } else {
     $twav_suffix = 'b';
    }
   } else if ( 'full' == $id_or_email['type'] ) {
    $twav_size = BP_AVATAR_FULL_WIDTH;
    $twav_suffix = 'b';
   } else if ( 'thumb' == $id_or_email['type'] ) {
    $twav_size = BP_AVATAR_THUMB_WIDTH;
    $twav_suffix = 'n';
   }

   $out = 'http://img.tweetimag.es/i/'. str_replace($twc_user_login_suffix,"",$user_info->user_login) . '_' .$twav_suffix;

   $avatar = "<img alt='Twitter Avatar' src='{$out}' class='avatar avatar-{$twav_size}' height='{$twav_size}' width='{$twav_size}' />";
   return $avatar;

  } else {
   return $avatar;
  }

 }

 // Check if Twit Connect exists (since its without it this function is pointless)
 if( function_exists( 'twit_connect' ) ) {

  add_filter( 'bp_core_fetch_avatar', 'bp_twc_get_avatar',10,4);

 }

?>

Show me the original version

I will add an explanation of what its doing if people are interested/curious.

·•·

Introducing WPAPI.ORG

Ok, so I actually launched this last weekend, but I’m only just now getting around to writing (briefly) about it. WPAPI.ORG is a super easy to use API which you can use to retrieve stats for all those great plugins and themes that you’ve got hosted on WordPress.org. Why would you want to do this?

Ok, so I actually launched this last weekend, but I’m only just now getting around to writing (briefly) about it. WPAPI.ORG is a super easy to use API which you can use to retrieve stats for all those great plugins and themes that you’ve got hosted on WordPress.org. Why would you want to do this?

WPapi.org

Why did I build this thing?

Because I could. No, seriously, the reason that I’ve built this (and made it available to everyone else) is that I was looking for ways to pull back the stats from WordPress.org and display them on the project pages here on my site, maybe even with some sexy graphs using something like Raphaël JS. After some investigation I found the xml feed that powers the graphs on WordPress.org, but that didn’t really help me. What I really wanted was JSON.

» Continue reading “Introducing WPAPI.ORG

Article 18 Oct 2009 0 comments
·•·

How to add clickable hashtags to your twitter widget

A few weeks ago Twitter finally added clickable hashtags to twitter.com. However if your one of the many people who make use of the html/js widget provided by twitter to display recent tweet on your own website then you will have noticed that you still don’t get clickable hashtags in the list of tweets that get displayed. Luckily this is pretty easy to fix if you want to, and you aren’t freaked out at the thought of modifying a little javascript.

A few weeks ago Twitter finally added clickable hashtags to twitter.com. However if your one of the many people who make use of the html/js widget provided by twitter to display recent tweet on your own website then you will have noticed that you still don’t get clickable hashtags in the list of tweets that get displayed. Luckily this is pretty easy to fix if you want to, and you aren’t freaked out at the thought of modifying a little javascript.

UPDATE: This article is no longer relevant, twitter have completely changed their widgets (which you can grab here), and the new widgets now support hashtags out of the box. Looks like any existing widgets should continue working as they just use the user_timeline API method which hasn’t changed.

Below is the default javascript function that is called by the default HTML Twitter widget, you can grab the widget code here or look at the full javascript file here.

There isn’t much to it, just the callback function, and a function to format the timestamp for each tweet. I’m only focusing on the callback in this post as that is all we need to play with to get clickable hashtags working. The default callback runs through the list of tweets that have been returned and using a couple of regular expressions (regex) it pulls out urls and @mentions and links them up.
» Continue reading “How to add clickable hashtags to your twitter widget”

Article 26 Jul 2009 4 comments
·•·

Modernizr is a small and simple JavaScript library that helps you take advantage of emerging web technologies (CSS3, HTML 5) while still maintaining a fine level of control over older browsers that may not yet support these new technologies. Could possibly be made even more powerful if combined with something like this CSS browser selector

Link 2 Jul 2009 0 comments
·•·

DotNetNuke — Not Good Enough

See what happens when you ask for a discussion around something that’s really been getting up my nose for the last 6 months, I go and write. I vent. I rant. But that’s what my blog is for, and thankfully it doesn’t run on DotNetNuke. So you want to know what I really think, keep reading.

Background

It all started with a tweet, the intention wasn’t to cause trouble, but to simply highlight what I thought of the contents of the post in question. I got a reply surprisingly quick from the co-founder who suggested “It is easy to take a shot at someone in abstract…”, and then “how bout a real discussion on the merits or lack thereof of his points”. Ok, let me elaborate.

Disclaimer
I’ll get this out of the way now, this is my blog so I’m entitled to my opinion, but so are you. If you don’t agree with my opinion, that’s fine with me, I don’t care at all. However, if you’ve never tried to use/customise/configure/upgrade/install this steaming p.o.s. then hold back any disagreement with me until after you have. Note: I’m not forcing you to try it out, that would be mean..

Retort — ask and ye shall receive

Those who work on DotNetNuke seem to be constantly defending themselves over the openness of their open-source project, so much so that I’m sure there are more defensive efforts than actual attacks. Despite what I think of their “openness”, I’m not here to specifically attack how open it is. Well not to begin with anyway, we’ll see what happens once I get going.
» Continue reading “DotNetNuke  —  Not Good Enough”

·•·
·•·
·•·

Easy CSS Drop Caps

Adding drop caps to the beginning of a paragraph, as I did with my latest redesign, is actually a pretty simple and straight-forward process. The effect can be achieved with just a couple of lines of CSS making use of two special ‘pseudo-elements’.

This effect should work in most browsers (yes, even Internet Explorer, according to MSDN both ‘elements’ should work in IE5.5+), the only real variation may be which font is displayed for the drop cap, and the way the specific browser interprets ‘em’ font-sizes. Alternatively pixel sizes could be used for the drop cap font, which should allow you to get greater consistency between browsers.

As mentioned we’re going to use two pseudo-elements as outlined in the CSS2 specification, the two ‘elements’ in question are :first-line and :first-letter. If you’re curious and want to know more about these ‘elements’ or the concept of ‘pseudo-elements’ feel free to follow the links and have a read of the specification, its not necessary for the purposes of this brief how-to, but some people are into that sort of thing.

» Continue reading “Easy CSS Drop Caps”

·•·

Racesquad

Just after Christmas I began work on my most recent project (yes I probably should have been doing one of the other dozen projects I’m always talking about). RaceSquad is a fantasy motorsport manager/game that I’ve built from the ground up based on the things I’ve liked and disliked in the many other similar ‘programs’ I participated in over the years. If you’re a motorsport fan, why not sign up to see what you think, feedback is more than welcome. http://racesquad.com

·•·
twitter was not updated. | lastfm was not updated. |