Today, during one of the soft redesign of Assembling I found myself in need to know whether an attachment was an image or not; the wordpress documentation did not give me any clue about how to do this - so I started to create myself the function I needed: get_the_attachment_type
It sits in my theme functions.php - and might be of any use to someone else:
<?php
function get_the_attachment_type($id = 0) {
$id = (int) $id;
$_post = & get_post($id);
$mime = $_post->post_mime_type;
return $mime;
}
?>
I use the function in the attachment.php file in the following manner:
<?php switch (get_the_attachment_type($post->ID)) {
case "image/jpeg":
case "image/gif":
case "image/png":
break;
default:?>
<p><b>Download</b>:
<?php } ?>
<?php echo $attachment_link; ?> <?php the_content(); ?>
This will then output a bold Download prompt in front of the file’s name in case, the attachment file is not an image (pdf, zip, etc.); if the attachment is an image, then nothing will be displayed.
I think the type is stored in the attachment meta data:
wp_get_attachment_metadata
applied to the attachment metadata retrieved by the wp_get_attachment_metadata function. Filter function arguments: meta data, attachment ID.
Comment by tt — April 1, 2008 @ 1:15 pm
Nice, I had to hit my head against the table a few times when trying to find a solution to this problem. Your solution looks more stable than my hacks.
It’s remarkable that you sometimes can’t find anything online, when dealing with problems so simple — especially when it’s Wordpress.
Comment by Anders — December 16, 2008 @ 11:56 am
Hi Anders - nice to read you after quite a long time; i’m happy this might have helped you. I’m working again on a project relying quite heavily on attachement and the new media library - more to come most certainly…
Tommi: cool. thanks for the tip on wp meta data. i will have a go this time with that as well
Comment by jerome — December 17, 2008 @ 2:14 am