I am a designer, a blogger and a Wordpress nut!

Subscribe to my Feed

WordPress Relative Links Inside a Post with Shortcode API

shortcode

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.

About the Author

Roy Ho is a web site design and developer. He blogs tutorials and articles on web design and development to share with the community. He has been practicing this field for 12 years now. He is passionate and very eager to learn more!
This entry was posted in Articles, Tutorials, Wordpress and tagged , , , , . Bookmark the permalink.
Back to top

48 Responses to WordPress Relative Links Inside a Post with Shortcode API

  1. Val Archer says:

    cool, thanks, works great! I’d like to post more but your comments feature won’t let me

  2. Val Archer says:

    Do you know of a way to define caption alignment separately from image alignment, for every image? e.g. left-align caption under a center-aligned image?

    I’ve tried everything including inline style, which I can’t demo here because doesn’t work in your comments :)

    All I can do so far is make *all* captions left-aligned OR all captions centered, with this in the css:

    .wp-caption {text-align:center}

    But I need control over each individual caption.

    thanks! - Val

    • Roy Ho says:

      Hi Val,

      You don’t need to give it text-align, instead use margins to push it left or right depending on your preference.

      For example .wp-caption { margin-left:-20px;}

      Like so…

  3. Val Archer says:

    But I have hundreds of images + can’t define different margin for each one in css. I need a hack for the missing “Caption Alignment” in admin’s “Edit Image” panel. All I can choose is Image Alignment + wp gives caption the same alignment. I need, e.g. “right” for image align and “left” for caption align, so a caption is left-aligned directly under a rightalign image.

    Can you figure a way to selectively impose an alignment on a caption regardless of it’s corresponding image’s position?

    thanks!

    • Roy Ho says:

      It’s better if you show me where you want to change so I can see the code that you are working to tell you how to do it…

      Show me the site that you want to change.

  4. Val Archer says:

    Hi Roy – thank you for your response. I’m converting my site into wordpress in wamp on my hard drive, so there’s no URL. The site I’m changing is greensmoothie.com – that’s in ‘s, not css. But you can see there’s lots of images and sometimes an image is right-aligned or centered, but if the caption text is very long, then I need it aligned left under the image. WordPress doesn’t seem to have that capability to separate caption alignment from image alignment.

    thanks! Val

    • Roy Ho says:

      It is not WP’s job to align the images but the job of the designer. I assure you it can be done.

      Once your site is up live, shoot me an email, I will help you out.

      • Val Archer says:

        thanks! It’ll be a while :) I tried in-line style in caption, to try force it to align differently from image-align, but it didn’t work, even when I used mime_type to stop wpautop from filtering it out.

        Can you try playing with it? Try get a caption to alignleft with an image that is aligned right – without defining all captions to alignleft in the css, and without defining individual captions in the css.

        How to selectively impose alignment on caption regardless of its image’s position?

  5. Roy Ho says:

    @Val
    While I don’t fully understand what you’re trying to do, based on my comprehension of your message, you are trying to selectively align text to the left under an image?

    Anything that you do selectively, can be done with class assignments in CSS. If you wanted only a certain caption to be aligned left, you assign a class for that particular caption ONLY and inside your CSS you style it accordingly.

    But it doesn’t make sense to selectively align a caption to be aligned left and when other captions are not. Or maybe I don’t fully understand what you’re trying to do.

    • Val Archer says:

      Hi Roy – I got a sample page up:

      http://www.greensmoothie.com/1gs/

      And here I describe the problems with captions that I’m encountering in wordpress:

      http://www.greensmoothie.com/tmp/roy.html

      Best to open both pages at the same time in separate tabs :)

      thank you for your kind help! – Val

      • Roy Ho says:

        If you want to link only to specific words in “Go to photos” simply place the anchor tag on ONLY that text. You don’t need to wrap the only thing in anchor tag.

        As for the caption alignment under the photos, you don’t need to float the text left, the text should naturally fall on the left side per document flow and for the ones you do want centered, just give it some margin to push it over or text align those. You can have separate CSS one to control the caption that needs to be centered and one that needs to align left.

        As for the tags WP puts in for you, you can download a plugin called RAW HTML Capability. That let’s you put in RAW code without having to fight with WP posts.

        Also could you email me instead so we can keep this post on topic royho @ 1plusdesign DOT com

  6. Fabry says:

    Hi look that if u would use a relative path for u’re wordpress
    u can use this simply function offers by WordPress GoodJoin

    http://codex.wordpress.org/Template_Tags/bloginfo

  7. Val Archer says:

    Hi Roy – please can you tell me how to change this line

    get_option(‘home’) . ‘/wp-content/themes/…

    so that it returns the URL of my root folder (where wp-config.php is)? As you mention, the above returns the URL of theme folder.

    I have a lot of folders and files that are off the wordpress root folder (but are not part of wordpress) that I need to refer to relatively from within posts, with something like:

    a href=”[root]/articles/one.html”

    Thanks also for your reply in forums, very helpful – Val

  8. Val Archer says:

    Hi Roy – that returns:

    http://articles/one.html

    whereas my wp-config (wordpress root folder) is in:

    http://localhost/1gs/

    so I tried this:

    return get_option(‘home’) . ‘/’;

    and it gives:

    http://localhost/1gs//articles/one.html

    whereas I need:

    http://localhost/1gs/articles/one.html

    - single slash after /1gs

    I can do this in Edit Post:

    a href=”[root]articles/one.html”

    and get the correct single slash:

    http://localhost/1gs/articles/one.html

    But I’d prefer to make it consistent with the relative image link, namely (I’ve used ‘rel’ in place of your ‘Posts’):

    img src=”[rel]/imgpg/top.gif”
    a href=”[root]/articles/one.html”

    Is there a way to change the functions.php so as to eliminate that extra slash? This produces the double slash:

    return get_option(‘home’) . ‘/’;

    thanks! – Val

    • Roy Ho says:

      Something tells me your site structure is not setup correctly..

      Why would you have http://articles and http://localhost on the same server?

      articles should be within the localhost not at the same level…

      It is really hard to give you help since I don’t exactly know why you’re doing the way you’re doing. Perhaps if you could draw up a clear tree structure of your site, it would be easier to help you. Currently it seems you have a static site but then you have WordPress inside another folder…etc. Do you still need the static site since you’re switching to WordPress?

      • valarcher says:

        Hi Roy – sorry you misunderstand.

        your: “return get_option(‘../home’) . ‘/’;” gives the link: http://articles/one.html

        whereas I need the function to give me the link: http://localhost/1gs/articles/one.html

        /1gs is where wp-config is. I need the function to return WP root folder, not theme folder.

        Now my edit “return get_option(‘home’) . ‘/’;” will take me to WP root so long as I enter it in Edit Post as: a href=”[root]articles/one.html”

        I’d prefer to be able to enter it as a href=”[root]/articles/one.html” – in other words find a way to delete a / from “return get_option(‘home’) . ‘/’;”

        It’s not critical :) I can enter in my Post “[rootfolder]articles/name.html” + “[themefolder]/images/name.jpg” – just have to remember that one takes a slash + the other doesn’t.

        thanks, Val

  9. Roy Ho says:

    @Val

    If you want to omit one slash simply use “return get_option(‘home’);”

    Above returns the “home” address set inside your WP admin settings and if you change it to “siteurl” then it returns the WordPress web address inside your WP admin settings.

    Hope that helps…

  10. valarcher says:

    Hi Roy – return get_option(‘home’); displays [root]/articles/one.html as: http://localhost/articles/one.html – whereas my wordpress URL in settings is
    http://localhost/1gs — I’m trying to get the function to return: http://localhost/1gs so I can enter in post: [root]/articles/one.html and the link will display as http://localhost/1gs/articles/one.html.

    My blog URL in settings is also http://localhost/1gs so ‘siteurl’ gives the same wrong link: http://localhost/articles/one.html.

    So neither ‘home’ nor ‘siteurl’ are returning the correct URL’s in settings – unless of course I add ” . ‘/’;” in which case [root]/articles/one.html will display as http://localhost/1gs//articles/one.html – with the double slash.

    thanks! – Val

  11. j says:

    WARNING !!

    I tried this and it works for an image or two except that after doing it to a few images it broke my theme and gave me the white screen of wordpress death.

    while it was breaking it gave me a couple of errors about already adding headers or something and then did an academy award winning western flick death.

    very dramatic

    • Roy Ho says:

      I am sorry to hear your problem but I can a sure you it wasn’t caused by the technique I provided.

      When you have security header errors, it usually means you have did something wrong in your functions.php file where either you have empty space/line or extra commas somewhere.

      Please double check…

  12. nike dunk shoes says:

    nice share, good

    article, very usefull for me…thank you

  13. Alex says:

    works great. I changed it so I can link to any page (relative link), in case web site URL changes. Thanks

  14. swapana says:

    Hi Roy,
    nice share, good article.
    need help: I want hide the all images path in my wordpress blog. Example:www.sitename.com/images/abc.gif to http://www.sitename.com/cM4kzb. If you know the any idea please share.

    • Roy Ho says:

      Hi swapana,
      Yes you can. What you need to do is use a mod-rewrite. You can do this directly in the Apache config or use your htaccess to do it. If you have permalinks set in your WP, then you should have this file generated by WP already. Just put in the URL you want to rewrite to and it should be directed automatically. For more info on mod-rewrites, just type it in on Google and you should have all the references you need.

      Hope that helps!

  15. Hey Roy,

    I’ve been enjoying your articles, very informative. I got a quick few questions I hope you can help me with!

    1: I’m in the process of moving a site from Joomla to WP, am I correct in assuming I can mass search & replace the absolute root url with the above shortcode and it would work?

    2: Does the shortcode also get triggered when it is used in a custom field in a post(in my case, images, I do not plan to migrate hundreds of images into WP’s media manager, I prefer my own folder structure.)
    , and this custom field is requested from within another function? And what about if requested from within the loop?

    3: Parts of the site use https, to keep my certificate valid any links, to images for example, need to change along of course, automatically, is that taken care of by get_option(‘home’), or do I need to add some sort of check for that to this function?

    Thanks in advance for your time :-)

    • Roy Ho says:

      Hi Ilja,
      1. The shortcode is used on pages and not template files. The point of it is to have relative link functionality in pages. If it’s in the template, you won’t need this function as you can use relative links in there by calling WP get_option functions.

      2. Good question. I have not personally tried this. Again if you’re talking about the loop, you can call relative links from get_option functions.

      3. You should have no problems here with this in regards to SSL.

  16. tamilly says:

    Great tip! I was dreading having to manually rewrite absolute paths when I finally make the site live, but your shortcode has made the whole thing a cinch. Thank you!

  17. Silverback says:

    WOW! This is AMAZING solution, THAX for this a lot!

  18. Silverback says:

    I have one quick question – can i handle this solution even for “text area” in widgets sidebar? I mean – i have some images in sidebar inserted by “Text” widget and i want to use this function too, but it don’t work the way as for posts and pages. Can you help me?

    • Roy Ho says:

      Hi Silverback,
      That’s because in sidebar widgets, shortcodes don’t work by default. You have to explicitly turn it on. If you open up your functions.php and add in “add_filter(‘widget_text’, ‘do_shortcode’);” (without the quotes) and it will work…

  19. Greg says:

    This is exactly what I am looking for, but unfortunately it isn’t working for me.

    I added the code as you outlined in themes/2010-weaver/functions.php:

    function myPostsLink() {
    return get_option(‘home’) . ‘http://example.com/wordpress/wp-content/uploads/2011/06/';
    }
    add_shortcode(‘Posts’, ‘myPostsLink’);

    (obviously example.com is for illustrative purposes only, not the actual website I am working on)

    I them went into my post and change the image from:

    to:

    The image is not displayed. I am using WordPress 3.1.3.

    Am I missing a step, or any idea about what I am doing wrong?

  20. Greg says:

    I did, and the image still doesn’t show up.
    It looks like my shortcode didn’t get displayed here, so I’ll try again with a modified syntax:
    (img src=”|Posts|/Fisher-Valve1-300×291.jpg”)

    The () are actually lt/gt
    and
    the | are actually sq brackets []

    • Roy Ho says:

      @Greg – You didn’t adapt it to how you’re using it…In my example it was for custom image folder…But you’re using the WP image upload folder so you don’t need to put all the stuff you did…in your function just put one slash… ‘/’. like that.

  21. Greg says:

    Thanks, I got it! I was missing the leading /.
    Appreciate the tip!

    • Roy Ho says:

      @Greg – please read my latest comment..if you use it the way you are now, you are limited to that post image…Do what i mention above and you can use this shortcode on any post…

  22. Scott says:

    Hi Roy,

    I just wanted to say THANK YOU for your tutorial. I’m not really a WP programmer (more of a web designer) and your tutorial wasn’t exactly what I was looking for per se but after looking at how you structured your shortcode example, I was able to use that and create some shortcodes for my theme options page which is awesome!

    I didn’t even know you could have a href=”[shortcode]” type of thing to represent a URL but I tried it based on your tutorial and it worked so many many thanks for providing your tutorial!

    Just wanted to say thanks

    Cheers mate

    Scott

  23. Passerby says:

    If you’re going to manually curate your links, why not just make them true relative urls?

    When using the ‘insert media’ button, it automatically pastes the absolute url – like “http://dev-domain.com/…/image1.jpg”. Your proposal is to then switch to the HTML mode and replace the “http://dev-domain.com” with a shortcode.

    But if you’re already there, just remove the domain, leaving the initial “/”. This link will then work regardless of what domain you move/copy/export the content.

    Am I missing something?

  24. Gerard says:

    Thnx for this “trick”.
    Seems also to work with version 3.2.1 :)
    Just a quick question (newbie here, sorry)
    Can I “rename” myPostsLink to myWhateverLink without any harm or does it have to be myPostsLink ?

  25. Gotequity says:

    I’ve implemented your solution successfully, but have noticed on several pages that my siteurl is output as text above the images. Do you know of a solution to prevent this from happening? I’m developing a client site in WP3.3 using a static url, and really want to get this working so I can avoid doing SQL rewrites once the domain is fully transferred. Thanks in advance.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*