3

Is there any way to order attachments by filename within a WP_Query?

For example, in the arguments:

$args = array(
    'post_type' => 'attachment', 
    'post_status' => 'inherit',
    'post_mime_type' => 'image',
    'order' => 'DESC',
    'orderby' => 'filename'
);

2 Answers2

0

There are no orderby filename option in get attachments argument. You need to sort by yourself attachments array based on available value from attachement array. To sort by filename you may use guid value.

Please read this link to sort array by value php array sort within array based on the value

Community
  • 1
  • 1
rheeantz
  • 960
  • 8
  • 12
0

Try something like this.

basename gives you each attachment filename and you can sort by that using usort. If you change the comparison operator (> to <) or switch return values (-1 : 1 to 1 : -1) the result will be reverse.

$args = array(
    'post_type' => 'attachment', 
    'post_status' => 'inherit',
    'post_mime_type' => 'image',
);

if ( empty( $images = get_posts( $args ) ) ) {
    return;
}

usort( $images, function( $img1,  $img2 ) {
    return ( basename( $img1->guid ) > basename( $img2->guid ) ) ? -1 : 1;
} );
Taku Yoshi
  • 141
  • 6