I've used this query to randomly select a total of $limit
-images (attachments), each from a unique and randomly selected parent.
$query="SELECT {$wpdb->posts}.post_parent, {$wpdb->posts}.ID
FROM {$wpdb->posts}
INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.post_parent = {$wpdb->term_relationships}.object_id)
INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id)
WHERE {$wpdb->posts}.post_type = 'attachment'
AND {$wpdb->term_taxonomy}.taxonomy = 'category' AND {$wpdb->term_taxonomy}.term_id IN ('{$wpdb->escape($category_filter)}')
AND {$wpdb->posts}.post_password = ''
AND {$wpdb->posts}.post_mime_type IN ('image/jpeg', 'image/gif', 'image/png')
GROUP BY {$wpdb->posts}.post_parent
ORDER BY {$order_by}
LIMIT {$limit};";
Unfortunately it has three faults:
I think the password-check is incorrect as it tests the attachment and not the parent_post, right? (does WordPress even support password protected gallery attachments?)
it certainly doesn't check the parent for
post_status = "publish"
it correctly selects random posts, but always the same pictures within them (the first one).
So - I humbly ask for your SQL-fu. How does one both select a random parent (first checking for published status) and then a random image ID owned by that parent, all in one query?
(I could select all attachments, ordered randomly and loop through them all and just grab the first $limit
from unique parents. But that leads to parents with lots of images getting selected too often.)