Wednesday 20 January 2010

WordPress Theme URL Tip

Lately I've been putting a lot of hours into developing a couple of sites using the WordPress and WPMU platforms. These platforms are a solid starting point for pulling a content/post based site together relatively quickly - the wealth of useful plugins also helps reduce the chance of you having to re-invent the wheel.

Having said that there is still a lot to do to create a professional website that has it's own look and feel - much of this can be achieved by creating a custom theme.

If you are creating a custom theme you will probably need to link to multiple elements within that theme's directory structure. The most common approach to do this is somthing like this:

<img src="<?php bloginfo('stylesheet_directory'); ?>/images/myimage.png">

echo '<img src="'.get_bloginfo('stylesheet_directory').'/images/myimage.png">';

I've certainly been using a lot of the latter style, until today.

I decided to clean up my code a bit and put the following line at the top of my theme's functions.php file:

if(!defined('WP_THEME_URL')) {
define( 'WP_THEME_URL', get_bloginfo('stylesheet_directory'));

Then I replaced all the get_bloginfo('stylesheet_directory') instances with the constant WP_THEME_URL. Now my code is a lot more readable and there is less typing.

<img src="<?php echo WP_THEME_URL; ?>/images/myimage.png">

echo '<img src="'.WP_THEME_URL.'/images/myimage.png">';

Using a constant like this should provide a slight performance increase here too - I haven't done any performance tests, but the current get_bloginfo() process is a fairly convoluted chain of function calls.

Note: Just in case the WP platform does start using this constant in the future, the constant's value is not set if it is already defined.

UPDATE: After this post was made I discovered WordPress defines a TEMPLATEPATH constant, but no constant currently exists for the TEMPLATEURL.


  1. Nice post i get good exprience from the post... waiting for new one. wordpress is the best CMS i think.

    wordpress security plugin best
    wordpress themes

  2. This is one of the greatest wordpres theme bro love you

  3. Today i have used this tip on my one website really a amazing too much great i love this

  4. If your business' website is struggling for first page placement on Google searches, then powering your site through WordPress is a good option for you. wordpress maintenance plans