Using WordPress ‘get_post_mime_type()’ PHP function

The get_post_mime_type() WordPress PHP function retrieves the mime type of an attachment based on its ID.

Usage

get_post_mime_type( $post );

Custom example:
Input:

$post_id = 42;
$mime_type = get_post_mime_type( $post_id );
echo $mime_type;

Output:

image/jpeg

Parameters

  • $post (int|WP_Post) – Optional. Post ID or post object. Defaults to global $post. Default: null.

More information

See WordPress Developer Resources: get_post_mime_type()

Examples

Display mime type of a specific attachment

This example retrieves and displays the mime type of an attachment with ID 42.

$post_id = 42;
$mime_type = get_post_mime_type( $post_id );
echo 'Mime Type: ' . $mime_type;

Check if attachment is an image

This example checks if the given attachment is an image.

function is_image( $post_id ) {
  $mime_type = get_post_mime_type( $post_id );
  return strpos( $mime_type, 'image/' ) === 0;
}

$post_id = 42;
if ( is_image( $post_id ) ) {
  echo 'The attachment is an image.';
} else {
  echo 'The attachment is not an image.';
}

Get all attachments of a specific mime type

This example retrieves all attachments with a specific mime type (e.g., image/jpeg) and displays their titles.

function get_attachments_by_mime_type( $mime_type ) {
  $args = array(
    'post_type'      => 'attachment',
    'post_mime_type' => $mime_type,
    'posts_per_page' => -1,
  );
  return get_posts( $args );
}

$attachments = get_attachments_by_mime_type( 'image/jpeg' );

foreach ( $attachments as $attachment ) {
  echo 'Title: ' . $attachment->post_title . '<br>';
}

Display a custom icon based on mime type

This example displays a custom icon based on the mime type of a given attachment.

function get_icon_for_attachment( $post_id ) {
  $base = get_template_directory_uri() . '/images/icons/';
  $type = get_post_mime_type( $post_id );

  if ( strpos( $type, 'image/' ) === 0 ) {
    return $base . 'image.png';
  } elseif ( strpos( $type, 'video/' ) === 0 ) {
    return $base . 'video.png';
  } elseif ( strpos( $type, 'text/' ) === 0 ) {
    return $base . 'text.png';
  } else {
    return $base . 'file.png';
  }
}

$post_id = 42;
$icon_url = get_icon_for_attachment( $post_id );
echo '<img src="' . $icon_url . '" />';