How to get the path to a file within a WordPress theme

There are two types WordPress functions that should be used when the getting the path to a parent or child theme directory.

Template functions are used for resources that are not intended to be over-ridden by a child theme.

  • get_template_directory()
  • get_template_directory_uri()

Stylesheet functions are used for resources that are intended to be over-ridden by a child theme.

  • get_stylesheet_directory()
  • get_stylesheet_directory_uri()

 

Returned values

These WordPress functions return one of the following

  • an absolute server path eg. /home/user/public_html/wp-content/themes/my_theme
  • a properly-formed URI ie. a web-address starting with http:// or https://

Note these functions do not return a trailing slash following the directory address.
 

Template functions

These functions retrieve the path to the directory that contains the theme templates. When using a child theme, these functions will refer to the parent theme.

get_template_directory()

Retrieves an absolute path to the directory of the current theme.
Use for including PHP files.

<?php include( get_template_directory() . '/includes/myfile.php'); ?>

get_template_directory_uri()

Retrieves a URI for the directory of the current theme.
Use for images, links, referencing additional stylesheets and javascript. Don’t use for loading PHP files or checking if a file exists.

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

 

Stylesheet functions

These functions retrieve the path to the directory that contains the currently activated stylesheet. When using a child theme, these functions will refer to the child theme.

get_stylesheet_directory()

Retrieves an absolute path to the directory that contains the stylesheet for the currently activated theme.
Use for including PHP files.

<?php include( get_stylesheet_directory() . '/includes/myfile.php'); ?>

get_stylesheet_directory_uri()

Retrieves a URI for the directory that contains the stylesheet for the currently activated theme.
Use for images, links, referencing additional stylesheets and javascript. Don’t use for loading PHP files or checking if a file exists.

<img src="<?php echo get_stylesheet_directory_uri() ?>/images/mypicture.png" />

 

References

From the WordPress Codex:

Leave a Reply

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