How to link to graphic assets within WordPress Themes

- by

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).



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

2 thoughts on “How to link to graphic assets within WordPress Themes”

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.