WordPress函数get_post_mime_type()获取附件[图片]的类型信息

描述:

获取附件[图片]的类型信息

用法:

<?php get_post_mime_type( $ID ) ?>

参数:

$ID

(integer) (可选) 文章ID

默认值: ”

示例:

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).'" />';

源文件:

/**
 * Retrieve the mime type of an attachment based on the ID.
 *
 * This function can be used with any post type, but it makes more sense with
 * attachments.
 *
 * @since 2.0.0
 *
 * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
 * @return string|false The mime type on success, false on failure.
 */
function get_post_mime_type( $ID = '' ) {
	$post = get_post($ID);

	if ( is_object($post) )
		return $post->post_mime_type;

	return false;
}