Short Post URLs

I just noticed a trend recently ( maybe not too recent ) on how to make your WordPress Post URLs short for sharing, especially with Twitter’s character limit.

I stumbled across Derek‘s post just the other day through a delicious share of Dean’s and since I’m working on a project with custom re-writes I thought it would be simple to write a quick plugin and document how to shorten your urls within your theme’s function file.

Another reason I thought this was justified: all the other plugins are too complex and Derek’s solution seems to be the best because it’s simple–it just needed to use what WP offers for custom rewriting vs. hacking the .htaccess file.

Right now it comes in two flavors, a plugin or you can update your function.php file within your theme.

add_action( 'generate_rewrite_rules', 'custom_rewrite_rules' );
function custom_rewrite_rules( $wp_rewrite )
{
$newRules = array();
// Defualt http://siteurl.com/s/1 ( '1' being the post id )
$newRules[ 's/([0-9]+)$' ] = 'index.php?p=' . $wp_rewrite->preg_index( 1 );
// Another example below http://siteurl.com/1
// $newRules[ '([0-9]+)$' ] = 'index.php?p=' . $wp_rewrite->preg_index( 1 );
$wp_rewrite->rules = $newRules + $wp_rewrite->rules;
return $wp_rewrite;
}

After you place this in your functions file, or after every update or new re-write, you will need to refresh your permalinks via http://yoursite.com/wp-admin/options-permalink.php ( just click save changes ).

Now you can just use Derek’s templating code to do something like this.