How to link to graphic assets within WordPress Themes

When you’re displaying graphics that are served from your own theme directory, hard coding is never a good idea. In fact it’s impossible because you don’t know your user’s URL.

There are a couple of built-in WordPress functions that can help us here. One of them is called get_stylesheet_directory_uri which returns the URL to your theme or child theme.

Here’s an example. Say you’d like to display the following file:

<img src="http://yourdomain.com/wp-content/themes/your-theme/images/your-graphic.png>

then you’d write this in PHP like so:

<img src="<?php echo get_stylesheet_directory_uri(); ?>/images/your-graphic.png">

This will work for both themes and child themes. If you are using a child theme and you’d like to explicitly call a file in the parent theme’s directory you can use get_template_directory_uri like so:

<img src="<?php echo get_template_directory_uri(); ?>/images/your-graphic.png">

Those options are great if you need the link, but what if you’re writing some PHP code and need the full server path to those files instead? Fear not, WordPress has functions for those situations as well – and they’re called the same thing, just without the _uri at the end (get_stylesheet_directory and get_template_directory respectively).





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.