Is there a way to get the URL of an image located in the theme folder? Or just get the URL of the theme folder?
3 Answers
You can use drupal_get_path()
to get the path to your theme folder:
$path = drupal_get_path('theme', 'name_of_theme');
From there you can specify a particular file like this:
$image_path = $path . '/images/image.jpg';
You could also use path_to_theme()
, but be wary as the return from this can change depending on the context it's called in:
It can point to the active theme or the module handling a themed implementation. For example, when invoked within the scope of a theming call it will depend on where the theming function is handled. If implemented from a module, it will point to the module. If implemented from the active theme, it will point to the active theme. When called outside the scope of a theming call, it will always point to the active theme.
-
Thanks for your help. And finally to make it URL, all I need is to add "$base_url" to the beginning of the path. Feb 20, 2012 at 13:03
-
1As an addition, it also possible to use function
file_create_url()
, so in the end to get absolute URL it's possible to call:$image_url = file_create_url($image_path);
Oct 19, 2012 at 11:13 -
A neato trick is also to get "path to current theme" which I use this function for: function get_theme_path(){ $themename = variable_get('theme_default', 'my_theme'); $themepath = drupal_get_path('theme', $themename); return $themepath; } Jul 2, 2014 at 14:25
-
if you arrive here looking for D9/D10 advice,
drupal_get_path()
has been deprecated and you;ll now want to use something like\Drupal::service('extension.list.theme')->getPath('seven')
drupal.org/node/2940438– SandraJun 7 at 16:28
$imgurl = file_create_url(path_to_theme().'/images/blah.png');
description: this line of code uses path_to_theme(), to get the path to the theme, and then file_create_url(), to create an url for the file, to get the URL of an image located in the theme folder, as requested by the op.
I got a downvote for not describing it, so there you are :-)
its also the same as the accepted answer, just with comments applied to make it more complete. please note that it refers to the theme folder of the current theme, so its mainly usefull inside a theme template.
-
If this line of code provides an answer to the question, it would be nice to include description for it. Apr 23, 2015 at 12:01
-
1If you have a multilingual page this is the method to go. drupal_get_path does not handle language prefixes in paths. so you might end up with a file path of /en/sites/all/themes/mytheme/image.png. file_create_url handles it properly. Jun 6, 2017 at 10:32
In Drupal 8
global $base_url;
$theme = \Drupal::theme()->getActiveTheme();
$image_url = $base_url.'/'. $theme->getPath() .'/images/image.jpg';