Wordpress: get_attached_media('image') sorted by title Wordpress: get_attached_media('image') sorted by title wordpress wordpress

Wordpress: get_attached_media('image') sorted by title


It would be better to fetch the attachments already ordered instead of ordering the result array, right? This would save you code, headaches and processing.

If you look at WP Codex, get_attached_media() calls get_children(), which calls get_posts() (yeah, that escalated quickly). In WordPress, attachments (and pretty much almost anything) is a post in essence.

Having all that in mind, this should fetch you the list of images attached to a post ordered by title:

$media = get_posts(array(    'post_parent' => get_the_ID(),    'post_type' => 'attachment',    'post_mime_type' => 'image',    'orderby' => 'title',    'order' => 'ASC'));

Edit: As pointed out by ViszinisA and Pieter Goosen, I changed the call to get_posts() directly. There was no point into calling get_children().

Note: The 'post_parent' parameter is needed, so I added it using get_the_ID() as it's value. Keep in mind that you need to be within the loop for get_the_ID() to retrieve the current post ID. When using outside the loop, you should change this parameter value accordingly to the context.