Getting Images from theme's directory in pages

Yes, I know that we have get_template_directory_uri(); in referencing to the theme's directory. It's working when I put the following code inside index.php or in header.php:

img src="?php echo get_template_directory_uri(); ?/images/sample.png"

But when I'm adding an image inside pages when editing via text, not in visual, it isn't working. How can I get the images from theme's images directory into the pages?

Thanks!

Topic directory images themes Wordpress

Category Web


<img src="<?php echo esc_url( get_template_directory_uri() . '/images/logo.jpg' ); ?>" alt="" >

Try this. It should work. You have to concatenate the results from get_template_directory_uri() and your images directory in echo.


get_template_directory_uri()

Quick search through WordPress core code, shows two different treatments. This function needs escaping when it’s used inside of tag attribute.

<img src="<?php echo esc_url( get_template_directory_uri() . '/images/logo.jpg' ); ?>" alt="" >

When used inside wp_enqueue_style() or wp_enqueue_script(), it is not escaped:

wp_enqueue_script( 'theme-customizer', get_template_directory_uri() . '/js/customizer.js', array( 'customize-preview' ), '', true );

However, looking at the function itself, it has filter right before returning values which makes it suspicious – it can be filtered in plugins and we don’t know exactly what’s returned. Rule of thumb in this situation would be better safe than sorry and always escape.


Shortcode is the way to go, something like this (in functions.php or as plugin) would work:

// [template_dir image="something.jpg"]
add_shortcode( 'template_dir', function( $atts ){
    return get_template_directory_uri() . '/images/' . $atts['image'];
});

It's not possible to use PHP code in editor. You can use an image with full path.

<img src="/wp-content/themes/your-theme/assets/images/1.jpg" />

In general I would avoid using theme specific images in the content, because when you change and delete the old theme, then they are gone. So I would consider using /wp-content/uploads/ for content images.



The answer is yes. You could run php code in editor. But that is not for proper way of adding images. Instead, you should create shortcodes to get those images from theme folder or use like below codes

<img src="/wp-content/themes/your-theme/assets/images/1.jpg" />

By removing domain name, it could even benefit of http requests. If removing domain doesn't work, you could even install php wordpress execute plugins. There are some plugins about it. To understand more, you should read this article. I hope that could solve your problems :). Good luck in codes.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.