The get_available_post_mime_types() WordPress PHP function retrieves all available post MIME types for a specified post type.
Usage
Here’s a generic example of how to use the function:
$post_mime_types = get_available_post_mime_types($type);
In this example, we’ll retrieve MIME types for the ‘attachment’ post type:
$post_mime_types = get_available_post_mime_types('attachment');
Parameters
$type
(string) (Optional) The post type for which to retrieve MIME types. Default: ‘attachment’
More information
See WordPress Developer Resources: get_available_post_mime_types()
Examples
Display MIME Types for Attachments
This example shows how to display MIME types for attachments in a comma-separated list.
$post_mime_types = get_available_post_mime_types('attachment'); echo implode(', ', $post_mime_types);
Get MIME Types for Custom Post Type
In this example, we will retrieve MIME types for a custom post type named ‘product’.
$post_mime_types = get_available_post_mime_types('product');
Filter Posts by MIME Type
This example filters posts by a specific MIME type, in this case ‘image/jpeg’, and displays the titles.
$args = array( 'post_type' => 'attachment', 'post_mime_type' => 'image/jpeg', 'posts_per_page' => -1 ); $query = new WP_Query($args); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); echo '<h2>' . get_the_title() . '</h2>'; } wp_reset_postdata(); }
Count Posts by MIME Type
This code snippet counts the number of posts by MIME type and displays the result.
$post_mime_types = get_available_post_mime_types('attachment'); foreach ($post_mime_types as $mime_type) { $args = array( 'post_type' => 'attachment', 'post_mime_type' => $mime_type, 'posts_per_page' => -1 ); $query = new WP_Query($args); echo $mime_type . ': ' . $query->found_posts . '<br>'; }
Display MIME Types as Dropdown
This example creates a dropdown to select MIME types, which can be used as a filter in a form.
$post_mime_types = get_available_post_mime_types('attachment'); echo '<select name="mime_type">'; echo '<option value="">All MIME Types</option>'; foreach ($post_mime_types as $mime_type) { echo '<option value="' . $mime_type . '">' . $mime_type . '</option>'; } echo '</select>';