Creating Custom Short URLs in Perch Runway
One of the nice little features we’ve had in the 24 ways site for a few years is custom short URLs. As full article URLs contain a sometimes lengthy slug based on the article title, it’s useful to have a shorter version to use in tweets and our ebooks.
Our publishing schedule dictates that we post once per day, and only 24 articles a year, so the short URLs are based on the date alone. For example, today’s article is the following:
https://24ways.org/201523
That’s the year 2015, followed by the day number, 23. Tomorrow will be 201524 and yesterday was 201522. All nice and predicable and logical and crucially, short.
In Perch Runway, we implement this using a route and tiny master page that looks up the full article URL and does a redirect. The route looks like this:
[year:year][i:day]
That’s a year (which we label as year
) followed by an integer (which we label as @day). The master page then queries the article:
<?php
$year = perch_get('year');
$day = perch_get('day');
$date = $year.'-12-'.$day;
$article = perch_collection('Articles', array(
'skip-template' => true,
'filter' => 'date',
'value' => $date
));
if (is_array($article) && isset($article[0]['slug'])) {
PerchSystem::redirect('/'.$year.'/'.$article[0]['slug'].'/');
}
We read in the day and the year, construct a date, and then filter the Articles collection to find the matching article. If we have a match, we redirect. Pretty simple, but very useful.