Stop hard coding urls in WordPress templates

A common mistake I come across when I’m working on WordPress themes is site urls and directory paths hard coded into template files. This is bad practice because if the site’s domain name ever changes, or if the theme is reused on another website, the urls won’t work.

WordPress has template tags that are meant just for this purpose. Specifically, home_url and get_template_directory_uri.

home_url

The home_url template tag does exactly what it says it does: gets the home url for the site, no matter what page the visitor is on.

For example, when including a “home” link in the header, instead of this:

<a href="http://website.com">Site Name or Logo</a>

Do this:

<a href="<?php echo home_url(); ?>">Site Name or Logo</a>

get_template_directory_uri

The get_template_directory_uri template tag is used for getting the current theme’s directory uri. Common use cases would be for loading images, or JavaScript and CSS files into your theme.

Let’s say you wanted to display your logo.

Instead of doing it like this:

<img src="http://website.com/images/logo.png">

Do this instead:

<img src="<?php echo get_template_directory_uri(); ?>/images/logo.png">

Likewise, to load your stylesheet, instead of this:

<link rel="stylesheet" href="http://website.com/style.css">

You could do this:

<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/style.css">

But an even better way to include scripts and styles in your theme is with the wp_enqueue_scripts hook, which you add to your theme’s functions.php file, like this:

function add_theme_scripts() {
wp_register_style( 'style', get_template_directory_uri() . '/style.css', array(), 1.0, 'all' );
wp_enqueue_style( 'style', get_stylesheet_uri(), array('style'), 1.0, 'all' );
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );

Note: get_template_directory_uri will only return the parent theme directory. If you need to get a child theme directory, use get_stylesheet_directory_uri instead.

Have anything to add, or did I leave something out? Leave your thoughts in the comments!

Leave a Reply

Your email address will not be published. Required fields are marked *