Sebastian
Sebastian

Reputation: 83

Wordpress: get_attached_media('image') sorted by title

I want to get all the images attached to a specific post. This works just fine with:

$media = get_attached_media('image');

What I need now, is to sort these images by their title. I can already produce a list of the titles that are in the array:

for ($i = 0; $i < count($media); $i++) {
  get_the_title(array_keys($media)[$i])
}

I have no idea how to sort this by title. Can anyone help?

Upvotes: 3

Views: 1677

Answers (1)

mathielo
mathielo

Reputation: 6795

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.

Upvotes: 7

Related Questions