Still relevant method of embedding images in WP Theme in 2018
Question
<img src="<?php echo get_bloginfo('template_url') ?>/images/logo.png"/>
Is the above still a relevant method of embedding images in the Wordpress theme or an obsolete?
If obsolete then what will be the correct method?
someone questioned me today that I am not doing it correctly?
Solution
someone questioned me today that I am not doing it correctly?
<?php echo get_bloginfo('template_url') ?>/images/logo.png
There are 2 possible reasons this could be considered 'incorrect':
get_bloginfo
is a very old function that does multiple things, this particular function was replaced byget_template_directory_uri
andget_stylesheet_directory_uri
- Security! You didn't escape anything! The entire thing should be wrapped in an
esc_url
OTHER TIPS
I still use this :
<img src="<?php echo get_template_directory_uri(); ?>/images/logo.png" width="" height="" alt="" />
Which works fine.
The main reason it might be considered outdated, based on the specific name you use for the image, is that since 4.5 IIRC there is a customizer setting which allows the user to upload "site image" which is usually used as a logo.
From a more HTML and semantic web point of view, this code is (and always was) wrong as the logo by itself is a meaningless image (which is why you are unlikely to add an alt attribute to it) and therefor it is a decoration which belong to CSS, either in a CSS file, or set as a background image of a link element if you let the user to have some control over it.
Other than using the above functions, there is a function specifically designed for getting the theme's dependencies. By using get_theme_file_uri()
, you can get the URL to any file included in your theme's folder.
Here's an example:
<img src="<?php echo esc_url ( get_theme_file_uri( 'images/logo.png' ) ); ?>"/>
It will automatically search for logo.png
and return it's URI if it exists. This function uses get_template_directory_uri
internally.