How to fix broken Wordpress URLs

Kirby follows a different approach for URLs than Wordpress does. This means that it's not that easy to keep your Wordpress-style URLs, when you are switching to Kirby.

With Wordpress, direct links to articles look like:

http://yourdomain.com/2012/05/31/how-to-fix-broken-wordpress-urls

…whereas with Kirby you get something like:

http://yourdomain.com/blog/how-to-fix-broken-wordpress-urls

…or

http://yourdomain.com/articles/how-to-fix-broken-wordpress-urls

…or

http://yourdomain.com/how-to-fix-broken-wordpress-urls

…depending on how you call your blog folder and whether you setup your blog as your homepage or not.

That's not so cool of course. If you or others already shared your articles, those links would be broken and your visitors would land on your error page.

Luckily, the Wordpress Exporter is smart enough to get the unique identifier for each of your Wordpress articles. In the case above, the unique identifier is…

how-to-fix-broken-wordpress-urls

The exporter will name the folder for each article by that identifier and thus the most important part of your article URL would still stay the same.

This also means that we only need a simple fix to redirect the Wordpress-style URLs to our new Kirby URLs.

Error template to the rescue

When a visitor tries to use one of the old Wordpress URLs:

http://yourdomain.com/2012/05/31/how-to-fix-broken-wordpress-urls

…Kirby would not be able to find a page for that and would display the error page instead. So what we need to do is to create a new template for that error page.

site/templates/error.php

In that template file, we will now check for the incoming URL and see if it is one of those old, broken Wordpress URLs with a rather simple regular expression:

<?php

// resolve broken wordpress urls (pattern: /YYYY/MM/DD/article-uid)
if(preg_match('!^[0-9]{4}\/[0-9]{2}\/[0-9]{2}!', $site->uri)) {

  // get the unique identifier for the article
  $articleUID = $site->uri()->path(4);

  // search for a matching article
  $article = $pages->find('blog/' . $articleUID);

  // redirect to that article
  if($article) go($article->url());

}

?>

// put the template code for your regular error page down here

So whenever a visitor would normally run into your error page, that error page will now be smart enough to detect, where your visitor wanted to go and redirects them to the correct page/article. This isn't even noticable except the URL in the address bar would change.

Please make sure that you change the location of your blog in that script, when you don't have your articles in a folder called blog.

I hope this makes it a little easier for you to get comfortable with Kirby.

blog comments powered by Disqus