I using the built-in gallery in wordpress to store and sort images inside a custom post type. In the theme I was using:
$attachments = get_posts(
array('post_type' => 'attachment',
'post_parent' => $post->ID,
'orderby' => 'menu_order'
)
);
The above code returns the gallery images correctly, but in the wrong order. When I look at the content field for the post containing the gallery, it contains the gallery data:
[gallery ids="2,5,7,8"]
So, my guess is that the built-in gallery doesn't store the sorting in a separate field like menu_order
instead it stores a sorted list of attachment ids in the content field of the parent post.
So my question is what would be the best way to get the gallery images sorted correctly from the theme?
I tried something like:
$matches = array();
if(preg_match('/ids="(.*)"/', $post->post_content, $matches)) {
$ids = $matches[1];
$query = "SELECT * FROM $wpdb->posts ".
"WHERE post_type = 'attachment' &&
post_parent = $post->ID ".
"ORDER BY FIELD(ID, $ids)";
$attachments = $wpdb->get_results($query);
}
This seems to work but is there a cleaner way of doing this.