Using WordPress ‘get_post_mime_types()’ PHP function

The get_post_mime_types() WordPress PHP function retrieves the default post mime types.

Usage

$mime_types = get_post_mime_types();

Parameters

  • None

More information

See WordPress Developer Resources: get_post_mime_types

Examples

Display supported mime types

This example retrieves the default post mime types and displays them in a list.

$mime_types = get_post_mime_types();

echo '<ul>';
foreach ($mime_types as $type => $label) {
    echo '<li><strong>' . $type . '</strong>: ' . $label . '</li>';
}
echo '</ul>';

Filter posts by mime type

This example filters and displays posts with the ‘image’ mime type using WP_Query.

$mime_types = get_post_mime_types();
$image_type = $mime_types['image'];

$args = array(
    'post_type' => 'attachment',
    'post_mime_type' => $image_type,
);

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        echo '<h3>' . get_the_title() . '</h3>';
    }
}

Custom mime type support

This example adds support for a custom mime type ‘video/x-mkv’ using the upload_mimes filter.

function add_custom_mime_types($mimes) {
    $mimes['mkv'] = 'video/x-mkv';
    return $mimes;
}
add_filter('upload_mimes', 'add_custom_mime_types');

Count posts with specific mime type

This example counts the number of posts with the ‘audio’ mime type.

$mime_types = get_post_mime_types();
$audio_type = $mime_types['audio'];

$args = array(
    'post_type' => 'attachment',
    'post_mime_type' => $audio_type,
);

$query = new WP_Query($args);

echo 'There are ' . $query->found_posts . ' audio files.';

Display mime type for each post

This example displays the mime type for each post in the loop.

if (have_posts()) {
    while (have_posts()) {
        the_post();
        echo '<h3>' . get_the_title() . '</h3>';
        $mime_type = get_post_mime_type(get_the_ID());
        echo 'Mime Type: ' . $mime_type;
    }
}