How to get the path to the current theme?

The question:

This code is used to get the directory of the current plugin: plugin_dir_url( __FILE__ ).

What should I use to get the directory of the current theme?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

I think you have to be a little careful because it depends on what you are trying to do.

If you are using a child theme get_template_directory(); will still go to the parent theme. However get_stylesheet_directory(); will go to the current theme, child or parent. Also, both these functions return absolute server paths.

If you wanted a fully formed URI, for links or images, you should use get_template_directory_uri(); or get_stylesheet_directory_uri(); using the correct one for the reasons stated.

Summary

Method 2

get_stylesheet_directory_uri is what you want. it returns the URL of the current theme. get_stylesheet_directory will return the file path on the server.

For example:

<img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/image.png" />

If you need the parent theme, get_template_directory and get_template_directory_uri are the equivalents.

If there is no parent theme then both will return the same value.

Further reading:


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment