Drupal – Getting the image path of a CCK field
By David Pratt / Tags: drupal / 3 Comments / Published: 26-01-10
I often find myself using the Views module in Drupal to generate SQL that I can then use elsewhere directly, such as from page handler include files. Occasionally however, the SQL that the View module generates doesn’t quite work as you would expect, or as though it would from within a standard View. This happens in my experience more often than not when you’re dealing with CCK image fields. The problem being that the contents of the 3 fields that are associated to a particular image within the content type table, don’t contain anything that resembles a path to the physical location of the image in the file system. The 3 fields that I am referring to can be identified by their endings; one will end in _fid, another with _list and the last with _data. To explain this better it might be easier if I give an example, the following SQL will get the contents of the 3 fields that are associated with an image, in this case it is the website logo field:
SELECT field_website_logo_fid, field_website_logo_list, field_website_logo_data FROM content_type_website LIMIT 1
When I perform this query I get:
fid: 1723
list: 1
data: a:10:{s:8:"duration"; i:0; s:6:"height"; i:0;s:5:"width"; i:0;s:18:"audio_bitrate_mode"; s:0:""; s:18:"audio_channel_mode";s:0:""; s:12:"audio_format"; s:0:""; s:13:"audio_bitrate"; i:0; s:17:"audio_sample_rate"; i:0; s:3:"alt"; s:0:""; s:5:"title"; s:0:"";}
You’ll notice that none of these values give anything obviously meaningful to work with, and this can be confusing because as you can see, there isn’t anything obvious here (to me anyway) that looks like an image path, or that can be used to construct an image path. You might be able to guess that the fid value can be used as a look up on another table to get more information about the image (which it can by the way), but you’d need to find that table and either do a join or an additional look up to find that out. Rather that doing that, the easiest method that I’ve come across to find the path of the image (if you know the fid value) is to use the field_file_load function like so:
$file = field_file_load($node->website_logo_fid); $filepath = $file['filepath'];
You could then put the $filepath directly into an image:
print '<img src="/'.$filepath.'" alt="" />';
Bear in mind that you might need to consider the base path before the $filepath.
The other instance that you might want to retrieve an image path from a CCK image field, is from within a template file. If you know the name of the CCK image field, then you can retrieve the path by doing something like:
$field_website_logo[0]['filepath'];
Subscribe via RSS
Twitter
Brendan May 16th, 2010 at 6:24 pm
Thanks David, and thanks Sasha for a great tip – this has helped me immensely this afternoon.