In the directory containing a custom module, I have a directory containing images.
How do I get the URL of those images?
In the directory containing a custom module, I have a directory containing images.
How do I get the URL of those images?
The easiest way, like referred above, is to use the relative path to site root:
'/' . drupal_get_path('module', $module_name) . '/img1.jpg'
Using it without the trailing slash in the beginning would break it on multiple level aliases, e.g. http://www.your_site.dev/category/2012/11/02/
A more complete example that works in Drupal 7 and 8. All other answers just show how to return the path to the module but not how to actually make a URL out of it.
<?php
$module_path = drupal_get_path('module', 'mymodule');
$image_path = "$module_path/images/img1.jpg";
$image_url = file_create_url($image_path);
// path
drupal_get_path('module', $module_name) . '/images';
file_create_url( drupal_get_path('module', $module_name) ) . '/images';
file_create_url
will always work in relation to default/files not the module directory so the URLs would end up like your_site.dev/sites/default/files/sites/all/modules/your_module/… which is incorrect. –
Hardie file_code_url
will return the URL under /sites/default/files. Thanks. –
Hebrides To get proper URL of your image you need to append base_path()
at the beginning of your image path. The correct URL would be:
$url = base_path() . drupal_get_path("module", "MY_MODULE") . "/image.png";
© 2022 - 2024 — McMap. All rights reserved.
drupal_get_path()
without a preceding slash was messing me up. – Cinchonine