Writing Image Paths in WordPress Themes the Right Way

wordpress Writing Image Paths in WordPress Themes the Right WayWordPress themes with hard-coded image paths are nightmares in the making. If the location of the theme files are moved or if any of the folder names are changed, the theme will no longer work. That is why the WordPress development team took the time to create a very useful function that finds the location of theme files.

Let’s say for example you want to display a logo image in the header of your theme. If you were designing the page with hard-coded paths, your hyper-linked image logo might look like this:

<a href="<?php echo get_option('home'); ?>">
<img src="wp-content/themes/theme-name/images/image-name.png" alt="logo" /></a>

Below is the proper way to code paths in WordPress themes:

<a href="<?php echo get_option('home'); ?>">
<img src="<?php bloginfo('template_directory'); ?>/images/image-name.png" alt="logo" /></a>

The function “<?php bloginfo(‘template_directory’); ?>” will automatically find the path to the theme you have enabled in the WordPress Admin Control Panel.

You can also use the bloginfo() function to locate paths to stylesheets, like in the following example:

<link rel=”stylesheet” type=”text/css” href=”<?php bloginfo(‘stylesheet_url’) ?>” >

Below Mitcho Erlewine, creator of the famous YARP (Yet Another Related Posts Plugin), talks at WordCamp San Francisco about abstracting your code so it is more reliable and easier to use for future developers.

Tags: , ,


You might like:

One Response to “Writing Image Paths in WordPress Themes the Right Way”

  1. indialoka says:

    But my guess is, the tag bloginfo(‘template_directory’), feature was already available from wordpress?

    Still it serves the purpose! And on the other hand, pagespeed says to “Serve static content from a cookieless domain” that includes the image content as well. I wonder if there is any solution from the wordpress side.. ;)

    <3 WP!

Leave a Reply

*