I'm trying to run a query to get all attachments and I'd like to sort by the post mime type. This query isn't working. Any ideas?

$query_args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => null, // any parent
'orderby' => "post_mime_type"
);  $attachments = get_posts($query_args);

2 Answers 2


As told by mrwweb you have to plug into Wp_Query orderby statement.

add_filter( 'posts_orderby', 'wpse53783_order_by_post_mime_type' );

function wpse53783_order_by_post_mime_type( $orderby ) {

    global $wpdb;

    $order = substr( $orderby, strpos( $orderby, ' ' ) );

    $orderby = "$wpdb->posts.post_mime_type $order";

    return $orderby;


You can apply the filter before the query then remove it with:

remove_filter( 'posts_orderby', 'wpse53783_order_by_post_mime_type' );

I didn't tested it but should fits your needs :)


get_posts() allows the same parameters and valueas WP_Query. As you can see from the Codex, "post_mime_type" is not a valid "orderby" value. Looking at the posts table in the database, I can see that "post_mime_type" is saved as part of the post object but not as a custom field or anything you could get at with a vanilla get_posts() or WP_Query instance.

I think that means your only option would be a direct query of the database (which I'm terrible at, so I'll spare you a code snippet). Hopefully someone else can come along and add one ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.