Jan

21

2010

Wordpress Relative Links Inside a Post with Shortcode API

0


In this tutorial I want to show you how to include “relative” links inside your Wordpress posts using shortcode API.

By default, when you are creating a post and want to include an image to spice up your content, you would declare an img tag statement and a source link that looks something like this img src=”images/image.jpg”. But you quickly realize that your image isn’t showing up on your content and you’re not too happy about that. To fix this problem, you end up declaring the source as an absolute source location.

No big deal right? Maybe…Many times as developers we create and test everything “offline” on a local environment. If you declared an absolute source location to a live server, what if you were not connected to the internet? Will you be able to see the image then? Absolutely not. But then you might argue that, “I am never off the internet”. Maybe so, but consider this scenario — many times I take my laptop out to see clients at a coffee shop or wherever and there happens to be no internet connection or I just don’t want to signup for it but I want to show my client the site I built for them in all its glory. Since I pointed the source location to a live server directory, my images will not show up. I would have to change it to an absolute location locally for it to work but imagine having to do that for every posts/content/pages every time I meet my client to show them something. You get the point…

So what is the solution to this problem? I am glad you asked because I myself have been frustrated with this when I first started with Wordpress as well. Now I want to pass this on to you guys so it makes your life easier. All hail the Shortcode API introduced since Wordpress 2.5…

You simply open up your functions.php file within your theme folder and add the following code.

PHP:

< ?php
function myPostsLink() {
	return get_option('home') . '/wp-content/themes/YOUR_THEME_FOLDER/';
}
add_shortcode('Posts', 'myPostsLink');
?>

Here we are simply declaring a function that returns the URL of your theme folder or whatever folder you choose. Then with the magic of the shortcode API, you can invoke the function “add_shortcode” with the first argument being the name of your choice and the second argument being the function name you are running.

After that, in your post, simply use “[SHORTCODE NAME]” or in this example “[posts]” and it will be replaced with the URL that you specified in the function. With this method, it will work in your local environment or on your live server without having to change it every time. Please keep in mind that the shortcode name is case-sensitive.

Armed with this technique, you can now use this to replace all your absolute links within your posts.

Back to top
  • Print This Post

Related Posts





Leave a Reply