I cringe every time I see a link in a blog post that is an absolute URL to other content on the same site. Here’s an example of what I mean:
In that example post you see a link to another page in my blog.
But what happens when you edit the slug of the post? The link will break.
Or what happens if you move your blog from
/news? The link will break.
Or even worse, what happens if you change the domain where the content is hosted from
http://blog.mysite.com? The link will break.
That’s why I cringe every time I see a link with an absolute URL to another page on the same site.
What’s the solution? Shortcodes.
Here’s an example of how to programmatically add links to your posts without being susceptible to the problems I mentioned above. The following code can be added to your theme’s functions.php file or to a custom plugin you might have.
After you add that code to your site, here’s how you can use it when writing a blog post or page.
To get the link to another post on your site all you need is the ID of the post you want to link to. Then in your post you would do something like this:
Now my link’s URL will be generated from the database and no matter how much we edit the other post’s slug or path, the correct URL will always appear in this link.
What if you want to avoid creating the
<a href="">...</a> HTML code? That’s easy. Just do this:
Now when the post is rendered, the <a> tag will automatically be created and the title of the post will show up.
If you want to control the title of the link, you can do this:
Let me provide one last example to clear up any confusion… Let’s say you wrote a post on your blog. The post you wrote is titled Hello, World!, it has a slug of hello-world and the post has the ID of 33.
Here’s what the shortcode would look like in your posts and what would be returned:
Hope this helps future-proof the links in your blog posts.