Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
add comment

2 Answers

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
add comment

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
add comment

Your Answer

 
discard

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.