1

What would be the proper way to add a group by to the media library query? What I have tired so far is not working:

add_filter('posts_groupby ', 'limitMediaLibraryItems', 10, 2 );
function limitMediaLibraryItems($groupby) {

    if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/upload.php' ) !== false ) {    
        $groupby .= " guid";
    }

    return $groupby;
}

Updated: Maybe the correct approach is to use the ajax_query_attachments_args filter. How could this be made to work?

add_filter( 'ajax_query_attachments_args', 'hide_duplicate_guids', 10, 1 );

function hide_duplicate_guids( $query = array() ) {

    $query['group by'] = 'guid';

    return $query;

}
4
  • What are you trying to achieve? GROUP are of very limited use in post queries. Also it's strange to see guid used as non–unique field?..
    – Rarst
    Nov 30 '14 at 15:40
  • It is not strange at all. Every item in the media library represents an attachment and some of our attachments will point to the same image file. By adding the group by we will eliminate duplicate images from the library.
    – AlanP
    Dec 1 '14 at 10:50
  • Could you elaborate on exact query and its SQL you are trying to modify?
    – Rarst
    Dec 1 '14 at 10:59
  • I would like to execute a query like this: SELECT ID, guid FROM wp_posts WHERE post_type = 'attachment' group by guid order by post_date
    – AlanP
    Dec 1 '14 at 13:51
1

I found a solution; use pre_get_posts:

add_action( 'pre_get_posts', 'modify_attachments' );

function modify_attachments( $query ) {
    if ( is_admin() && strpos( $_SERVER[ 'REQUEST_URI' ], 'admin-ajax.php' ) !== false ) {      
        add_filter( 'posts_groupby', 'group_attachments' );
    }
 return $query;
}

function group_attachments( $groupby ) {  
    $groupby .= " guid";
    return $groupby;        
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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