WordPress: Shortcode for Theme Location/URL

There has been a few occasions when building a WordPress site for a client that we have needed to insert an image into a post/page that was located within the theme folder. It can be quite a pain writing out the whole URL to the theme directory where the image is location. Also if the site URL or theme directory name was to change, the hardcoded path would instantly cause a broken image.

A nice little trick to get around this problem is to create a shortcode that will automatically output a site’s theme directory. Copy and paste the below code into your theme’s functions.php file and away you go.

function theme_url_shortcode( $attrs = array (), $content = '' ) {
	$theme = ( is_child_theme() ? get_stylesheet_directory_uri() : get_template_directory_uri() );

	return $theme;
add_shortcode('theme', 'theme_url_shortcode' );

Simply use the [theme] shortcode within a page or post and it will output your theme URL.

Example Usage

If you were referencing an image in your post, you would do something like this:

<img src="&#91;theme&#93;/images/image-name.jpg" width="250" height="250" alt="This is an image" />

Which would output something like this:

<img src="http://www.domain.com/wp-content/themes/theme-name/images/image-name.jpg" width="250" height="250" alt="This is an image" />
Free Graphics, Icons, Tutorials
Free Graphics Free Christmas Vector Icon Graphics Pack 2017Free Fitness Vector Icons Graphics PackFree Camping Vector Graphics PackFree Summer Graphics PackFree File Icon PackFree Fast Food Vector Graphics
Sharing is caring...
Like & Follow
Share the love, share this page! Facebook Twitter Digg Reddit LinkedIn Pinterest Email
Close [X]
The Web Taylor
1000 Lakeside North Harbour Portsmouth, Hampshire PO6 3EN
02392 123358