Calling an image within the theme folder from inside a post/page?

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.

Read More

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!

Related posts

Leave a Reply

2 comments

  1. 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:

    /**
     * Add a shortcode for the current theme directory
     * @return string Current theme directory
     */
    function yourtheme_get_theme_directory_uri() {
        return get_template_directory_uri();
    }
    add_shortcode( 'themeuri', 'yourtheme_get_theme_directory_uri' );
    

    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.