检查附件是否是图像

I am trying to display an image or video in the place of woocommerce product featured image based on the attachment type. For this, I am trying to check if the post attachment is an image or a video.

I googled and found that get_post_mime_type() will do that job and with the help of wordpress function reference page here, I added the following code but it is not giving me required output, the switch case is always going to default case and I am unable to check the attachment mime type. Did anyone face this issue earlier?

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

I didn't use this function. Another approach you can see :

    $file_url = wp_get_attachment_url($attachment_id);
    $file_parts = pathinfo($file_url);
    echo $file_parts['extension'];

While I suspect PHP might forgive you for your syntax, I think your switch logic is incorrect. There's no point putting a break after a return statement. This is the preferred way of coding it.

function get_icon_for_attachment($post_id) {
    $base = sprintf('%s/images/icons', get_template_directory_uri());
    $path = sprintf('%s/file.png', $base);
    $type = get_post_mime_type($post_id);
    switch ($type) {
        case 'image/jpeg':
        case 'image/png':
        case 'image/gif':
            $path = sprintf('%s/image.png', $base);
            break;
        case 'video/mpeg':
        case 'video/mp4': 
        case 'video/quicktime':
            $path = sprintf('%s/video.png', $base);
            break;
        case 'text/csv':
        case 'text/plain': 
        case 'text/xml':
            $path = sprintf('%s/text.png', $base);
            break;
    }
    return $path;
}

Don't worry about my usage of sprintf(), that's just what I prefer to use. If it's still returning file.png with my version of the function, then the attachment mime type isn't an image.

Or the attachment isn't one of the mime types you're catering for, like an .ico, .bmp or .tiff file.