I am building a website for a client of mine who would like the ability to make minor layout changes themselves. Because of this I am coding some of the layout directly into pages using the text editor. The problem I am facing is dynamically including an image from the template directory into the posts/pages.
Normally I would just use <img src="<?php echo get_template_directory_uri(); ?>/images/image.png">
but that doesn’t work when placing the code directly into a page/post since the raw text is outputted.
Can anyone tell me how I can dynamically include an image through the post/page area without using the media library(since I’d like to keep site assets separate from attachments).
Thanks!
I realize that this was posted about 7 months ago, but in case you’re still looking for a solution to this, add this to your
functions.php
file:Then in the WordPress Editor you can simply use the
[themeuri]
shortcode to include the URL of your currently active theme directory.Typically, you would want to include a shortcode like this as a plugin so that when you change themes the shortcode doesn’t disappear. However, because you’re using it to include media specific to your theme, I don’t think it matters.
And for those questioning why you would even want to do something like this: If the user who posted this question has theme-specific assets that need to be loaded in the Editor and might change but retain the same file name, this is a smarter, more future-friendly approach than using the Media uploader.
For example, in my own theme I have an SVG sprite that’s always named
icons.svg
but make include new icons or remove some over time. The sprite is generated as part of my Gulp build. An approach like this saves you from having to reupload and update URLs every time you update the sprite.It’s not super clear to me what you are trying to do (and why)… but you know you can change the Media Library upload folder to something out of the ‘WordPress directory’, so that your uploads all become, eg. http://www.yourdomain.com/files/media1.jpg etc.
Here’s a good basic tutorial on this.
Would that solve it for you?