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.

[sourcecode language=’php’]
add_action( ‘generate_rewrite_rules’, ‘custom_rewrite_rules’ );
function custom_rewrite_rules( $wp_rewrite )
$newRules = array();
// Defualt ( ‘1’ being the post id )
$newRules[ ‘s/([0-9]+)$’ ] = ‘index.php?p=’ . $wp_rewrite->preg_index( 1 );
// Another example below
// $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 ( just click save changes ).

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