Getting your site URL in WordPress

Posted

WordPress URL Functions

I’ve worked with WordPress for years, and one of the most common problems I see when looking at others code is the way they chose to get the path to their theme directory or the url of the site. A lot of front-end developers still don’t seem to really know what the best way is to do this essential thing in WordPress. Below are a few examples for pointing to urls or directories within WordPress:

  1. Getting your site URL: It’s a fairly common requirement, maybe you want to simply add a link to your home page? If you’re currently using bloginfo() for this then please stop! The code below gives a very basic example of how to do it the proper way.

    <a href="<?php echo home_url( '/' ); ?>">This is a link to your home page</a>

    If you’re in doubt of anything then read the Codex it really does help! By using the correct functions to get you around WordPress you make it much more likely that your theme won’t clash or interfere with plugins or other developers code. There is nothing more frustrating than trying to troubleshoot a bug in your own code only to find it’s another plugin that is causing the issue!

  2. Getting the theme location: If you are using TEMPLATEPATH or bloginfo( 'template_directory' ) stop, stop right now!! It’s much better to be using the very useful get_template_directory().

    There are actually 4 variations of this function:

    1. get_template_directory() returns the PATH to your theme folder. Useful for use inside PHP functions or includes.
    2. get_template_directory_uri() returns the URL to your theme folder. Useful for enqueueing and registering your scripts and styles and if you want to include and image.
    3. get_stylesheet_directory() returns the PATH to the stylesheet folder. This will always point to the Child Theme if one is in use whereas get_template_directory() will always point to the Parent Theme.
    4. get_stylesheet_directory_uri() returns the URL to the stylesheet folder. As with the above this will always point to the Child Theme if one is in use.

    For more examples of using these check out the official WordPress codex

    Try to make sure that you’re always using the best function for the job, especially if you are expecting users to override your theme in a Child Theme then it is best to use the correct function.