Print name and filename of the top-most file attached to a Drupal post
This is very much a hack, as it puts far too much database loading and PHP logic not even in the theme layer, but worse, embedded in the content itself. A better version might use the theme layer to make the $filename and other such variables available to certain content types with files attached, for instance.
For now... here's the hacky way. But first, some of the research to get us there:
php get first element of array
http://us3.php.net/reset
The files array with which we are dealing:
[files] => Array
(
[2] => stdClass Object
(
[fid] => 2
[uid] => 1
[filename] => scf_dist-6.x-1.0-alpha1.tar.gz
[filepath] => sites/default/files/scf_dist-6.x-1.0-alpha1.tar.gz
[filemime] => application/octet-stream
[filesize] => 19140109
[status] => 1
[timestamp] => 1221850324
[nid] => 2
[vid] => 4
[description] => scf_dist-6.x-1.0-alpha1.tar.gz
[list] => 1
[weight] => 0
)
)
So we have to sort it by weight first to get the first file listed.
Sort an array of objects by an object property in PHP. Basic approach:
<?php
$node = node_load(arg(1));
$files = $node->files;
function file_weight_sort($a, $b) {
if ($a->weight == $b->weight) {
return 0;
}
return ($a->weight < $b->weight) ? -1 : 1;
}
usort($files, 'file_weight_sort');
$file = reset($files);
$filename = $file->filename;
?>Resolution
Here it is, in all it's glory:
<!-- PHP code below gets the first file name and path and prints it as needed -->
<li><kbd>wget <?php
$node
= node_load(arg(1));
function file_weight_sort($a, $b) {
if ($a->weight == $b->weight) {
return 0;
}
return ($a->weight < $b->weight) ? -1 : 1;
}
$files = $node->files;
usort($files, 'file_weight_sort');
$file = reset($files);
$filename = $file->filename;
$filepath = $file->filepath;
global $base_url;
print $base_url;
print '/';
print $filepath;
?></kbd></li>
<li><kbd>tar -zxvf <?php print $filename; ?></kbd></li>More like this
- Making sure multiple numeric ID input can be allowed in the most flexible way possible
- Drupal's .info file parser versus PHP's .ini file parser
- Keep .DS_Store files out of your Git projects when developing on a Mac
- Combining first and last name form fields to make a suggested preferred display name with JQuery
- Search from a Drupal 404 File not found page
Comments
Post new comment