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
Hi Jerome,
Thanks for this great bit of code!
How hard do you think it would be to set up a conditional situation where the WP loop pulls different templates for different types of MIME types?
I’m thinking something like this would work:
if (case=jpg) { }
elseif (case=mp3) { }
etc…
Make sense?
Any help would be greatly appreciated.
Thanks.
Best,
Allan
Comment by Allan Cole — March 12, 2009 @ 11:18 am
hi Allan – if you are using 2.7 which i bet you are after quickly scanning yur blog, i think it’s better to use the wp_get_attachment_metadata which tt is speaking about.
If you want to use the bit i wrote a while ago, i suppose you can use PHP switch function: http://uk3.php.net/switch; when there’s a lot of different possibilities on the same level, i find it clearer to read rather than the if statements.
Good luck
Comment by jerome — March 12, 2009 @ 11:34 am