get_post_mime_type()
Retrieves the mime type of attachment posts (images, files, etc.), based on the provided ID.
The function can be used with any post type, but is designed specifically for attachment posts.
Uses: get_post()
No Hooks.
Returns
String|false. MIME type or false if there is no MIME type.
Usage
<?php get_post_mime_type( $post ) ?>
- $post(int/WP_Post)
- ID of the post.
Default: null
Examples
#1 Get a mime type of post
You need to get mime type posts with ID equal to 121 (this is a loaded in the media section of the WordPress html file):
$rrr = get_post_mime_type( 121 ); echo $rrr; // output: text/html
If we need to know the mime type inside a loop that uses the global variable $post, you can use this function instead:
$post->post_mime_type;
#2 Return an icon image path according to the MIME type of the given post
function get_icon_for_attachment( $post_id ) {
$base = get_template_directory_uri() . "/images/icons/";
$type = get_post_mime_type($post_id);
switch ($type) {
case 'image/jpeg':
case 'image/png':
case 'image/gif':
return $base . "image.png"; break;
case 'video/mpeg':
case 'video/mp4':
case 'video/quicktime':
return $base . "video.png"; break;
case 'text/csv':
case 'text/plain':
case 'text/xml':
return $base . "text.png"; break;
default:
return $base . "file.png";
}
}
// call it like this:
echo '<img src="'. get_icon_for_attachment( $my_attachment->ID ) .'" />';
WordPress already has a function to get the mime type icon called wp_mime_type_icon().
Changelog
| Since 2.0.0 | Introduced. |
get_post_mime_type() get post mime type code WP 7.0
function get_post_mime_type( $post = null ) {
$post = get_post( $post );
if ( is_object( $post ) ) {
return $post->post_mime_type;
}
return false;
}