WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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);
share|improve this question

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 :)

share|improve this answer

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 ;)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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