PHP Function to Grab WordPress Theme Location

June 25, 2013 Development, HTML, PHP, WordPress

PHP Function to Grab WordPress Theme Location

Sometimes when I look at WordPress code, especially on older sites, I’ll notice the following line of code:

HTML

<img src="/wp-content/themes/my-theme/images/my-image.jpg" alt="My Image" />

There are a couple reasons to not static code the theme location:

  1. WordPress may be installed on a subdirectory, making the location of the WordPress core not in the root directory
  2. The theme name may change which would break all of the images

The correct way to add this link to your theme is the bloginfo() function. You can see below that it replaces the “/wp-content/themes/my-theme” portion of the image URL.

HTML and PHP

<img src="<?php bloginfo('template_directory'); ?>/images/my-image.jpg" alt="My Image" />

Now your theme can be installed in any directory or with any name and still work just fine.

Let's Talk About Your New Website

View Portfolio Contact Today