How to use get_template_directory_uri() to load an image that is in a sub-folder of my theme?

How do I insert an image that is in a subfolder into my theme directory?

I have the following situation: Into my custom theme directory I have the following folder that contains a jpg image: /assets/img/flexslider/flex-1.jpg

Read More

Now in my header.php file, I have something like this:

<li>
  <img src="assets/img/flexslider/flex-1.jpg">
  <div class="flex-caption">
    <p class="flex-caption-text">
      <span>Lorem ipsum</span><br>
      <span>sit dolor</span><br>
      <span>adipiscing elitur</span>
    </p>
  </div>
</li>

Obviously, when I load the page, the image flex-1.jpg is not loaded because there is not the right path (in fact using FireBug I obtain that it try to load the assets/img/flexslider/flex-1.jpg image) so I think that I could use the absolute path but this is pretty horrible!

So I am thinking to use the get_template_directory_uri() function provided from WordPress to do this and I have tried to change the previous code in this way:

<li>
  <img src=<?php get_template_directory_uri().'/assets/img/flexslider/flex-1.jpg' ?>>
  <div class="flex-caption">
    <p class="flex-caption-text">
      <span>Lorem ipsum</span><br>
      <span>sit dolor</span><br>
      <span>adipiscing elitur</span>
    </p>
  </div>
</li>

But it is not working and using FireBug I can see that it is loading nothing, in fact in my browser source code I have:

<img src="">

What am I missing?

Related posts

2 comments

  1. You should echo it and also you are closing your php tag improperly. View source the o/p generated to get some idea

    img<src=<?php echo get_template_directory_uri()."/assets/img/flexslider/flex-1.jpg"?> alt="alternative_name">
    

    or you can use bloginfo which is easier to remember and use (You need not echo)

    <img src="<?php bloginfo('template_url'); ?>/assets/img/flexslider/flex-1.jpg"/>
    
    1. More Dynamic Way is in your functions.php file add this line

      add_theme_support( 'custom-logo' );

    2. New to display the image use

    $custom_logo_id = get_theme_mod( 'custom_logo' );
    $image = wp_get_attachment_image_src( $custom_logo_id , 'full' );
    echo '<img src=$image[0] height="100px" />';
    

    Know more

Comments are closed.