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
- Having the top-level menu items not be links (for use with dropdown menus)
- Attach a file to a Drupal page or post
- Using Ubiquity to post notes to Drupal
- Print information associated with a node elsewhere in page.tpl.php, using a separate template file for theming
- Printing an arbitrary menu just like primary_links and secondary_links


Comments
Post new comment