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.
If you were referencing an image in your post, you would do something like this:
<img src="[theme]/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" />