How to source your theme’s directory in WordPress

It’s important when developing in WordPress to utilise the built-in functions that are there to make our lives easier. Whether building a plugin or tailoring a theme, we often need to source a file from within our theme’s directory.

Obviously, this should never be hard-coded! Using our little friends bloginfo() and get_bloginfo() we can dynamically pull our theme’s URI wherever we are by appending them to bloginfo(‘template_directory’) and get_bloginfo(‘template_directory’).

Sourcing files within theme includes

If you’re working within a template file, then you can use the bloginfo() function to source files such as images or PDFs. Here’s the function in action, helping us locate an image within our theme’s ‘images’ folder:

<img
src="<?php bloginfo('template_directory'); ?>/images/slide_1.gif"
alt="" />

Sourcing files within PHP

When working with PHP, you simply need to switch over to the get_bloginfo() function in order to source your theme’s URI. This can be concatenated like in the example below for enqueueing a script:

function add_js_file() {

	wp_register_script( 'addjs', get_bloginfo('template_directory') . '/js/file.js','','0.0.1',true  );

	wp_enqueue_script( 'addjs' );

}

add_action( 'wp_enqueue_scripts', 'add_js_file' );