WordPress is, for the most part, pretty intuitive. However, one place where WordPress complicates things unnecessarily is in finding the current theme directory.
That’s not to say there aren’t intuitive ways of obtaining this information already built into WordPress:
Need the current theme URL? Use get_template_directory_uri()
.
Need the absolute path to the current theme directory? Use get_template_directory()
.
The confusion comes from the fact that WordPress also (and more commonly) refers to the directory of the current theme as the “stylesheet directory”.
To illustrate my point, here’s a handy example that will make sure an image file exists before displaying it:
<?php if (file_exists(get_template_directory()."/img/logo.png")) { ?>
<img src="<?php echo get_template_directory_uri(); ?>/img/logo.png">
<?php } ?>
We could just as easily and correctly (and confusingly, to my mind) write our example above like this:
<?php if (file_exists(get_stylesheet_directory()."/img/logo.png")) { ?>
<img src="<?php echo get_stylesheet_directory_uri(); ?>/img/logo.png">
<?php } ?>