Automatically generate your blog URL in WordPress posts
When writing WordPress blog posts, there are two types of internal URLs that I use often: URLs for images and files that I’ve uploaded to the site, and URLs to other posts. Both types of URLs are vulnerable to changes in my blog setup or blog URL. For example, consider an image at:
http://www.theblog.ca/wp-content/uploads/2008/05/documentation_icon_50px.png
This image URL has to be hard-coded into my post. If I change my site URL from theblog.ca to peterscrazyblog.com, that image URL is no longer valid. To fix this, I can add a redirect rule. However, that means that I must forever keep theblog.ca and that the generated URL still points to theblog.ca. Alternatively, I could code a relative URL (such as /wp-content/uploads…) that bypasses the domain altogether, but that breaks the images on sites that syndicate my content (such as Planet WordPress) and I’m still in trouble if I change the path to the folder that stores all the uploaded files and images.
Similarly, if I link to another post on my blog, that URL could change if I change my site URL or if I change my permalink structure.
The solution that makes sure my links remain valid and that they follow any changes I make to my site URL is to use what is called “shortcodes” in WordPress. (A shortcode is a piece of code that you can insert into a post that will be replaced with something else when the post is rendered.)
I know that my site URL and the path to the uploads directory are defined within the WordPress admin panel (under the Settings > General and Settings > Miscellaneous menus). They should only need to be defined once and never typed again. Therefore, I’ve created a plugin (compatible with WordPress 2.6 and higher) that enables you to use shortcodes to pull the already-defined site URL and uploads directory whenever you need to generate URLs that are within your blog.
Once the plugin is installed, the three shortcodes available when you’re writing a post are [blogurl], [posturl], and [templateurl].
On my site:
- [blogurl] will generate http://www.theblog.ca/
- [blogurl wordpress] will generate the URL to the root of your WordPress files, if they are in a different location than your site root
- [blogurl noslash] will generate http://www.theblog.ca
- [blogurl uploads] will generate http://www.theblog.ca/wp-content/uploads/
- [blogurl uploads noslash] will generate http://www.theblog.ca/wp-content/uploads
- [posturl id=375] will generate http://www.theblog.ca/blog-url-shortcodes
- <a href="[posturl id=360]">recent post about recycling</a> will generate recent post about recycling
- [templateurl] will generate the URL to your parent theme’s root
- [childtemplateurl] will generate the URL to your child theme’s root