Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 910279
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T17:01:03+00:00 2026-05-15T17:01:03+00:00

I’ve used this query to randomly select a total of $limit -images (attachments), each

  • 0

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};";

(full code at pastebin)

Unfortunately it has three faults:

  1. 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?)

  2. it certainly doesn’t check the parent for post_status = "publish"

  3. 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 $limitfrom unique parents. But that leads to parents with lots of images getting selected too often.)


“When the answer escapes you, change the question…”

I just released a plugin that enables bulk selection of a “featured post image”, directly from the media library. The core of my function went from ~45 lines to this;

foreach($potential_parents as $parent){
   if(has_post_thumbnail($parent->ID)) {
      $image = get_post_thumbnail_id($parent->ID);
   }
}

It’s not random but the site looks better and visitors have an easier time navigating content now that the thumbnails are consistent.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T17:01:04+00:00Added an answer on May 15, 2026 at 5:01 pm

    It’s not one query, but it’s a heck of a lot faster than the WordPress-hackery I posted earlier, and not very much slower than the original. I suppose it’s the price to pay for correctness and while being SQL-ignorant. 😛

    $potential_parents = $wpdb->get_results(
            "SELECT DISTINCT {$wpdb->posts}.ID, {$wpdb->posts}.post_title 
            FROM {$wpdb->posts} 
                LEFT JOIN $wpdb->postmeta wpostmeta ON ({$wpdb->posts}.ID = wpostmeta.post_id) 
                LEFT JOIN $wpdb->term_relationships ON ({$wpdb->posts}.ID = $wpdb->term_relationships.object_id) 
                LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) 
            WHERE $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->term_taxonomy.term_id IN({$wpdb->escape($category_filter)}) 
            AND {$wpdb->posts}.post_type = 'post' 
            AND {$wpdb->posts}.post_status LIKE 'publish' 
            AND {$wpdb->posts}.post_password = ''           
            ORDER BY {$order_by};");
    $imglists = array();
    $parent_titles = array();
    $count = $limit;
    foreach($potential_parents as $parent){
        $images = $wpdb->get_results(
            "SELECT {$wpdb->posts}.ID  
            FROM {$wpdb->posts} 
            WHERE {$wpdb->posts}.post_parent = {$parent->ID}
            AND {$wpdb->posts}.post_type = 'attachment' 
            AND {$wpdb->posts}.post_mime_type IN ('image/jpeg', 'image/gif', 'image/png') 
            ORDER BY {$order_by} 
            LIMIT 1;"); 
        if($images){
            $imglists[$parent->ID] = $images;
            $parent_titles[$parent->ID] = $parent->post_title;
            if(--$count < 1){break;}
        }       
    }   
    foreach($imglists as $parent_id => $imagelist){
        $imgurl = wp_get_attachment_image_src($imagelist[0]->ID, $size); 
        if($imgurl === false){continue;} //the image doesn't exist? 
        $img_width = $imgurl[1];
        $img_height = $imgurl[2];
        $imgurl = $imgurl[0];       
        $selection[] = array('post_url'=>get_permalink( $parent_id ), 'post_title' => wp_specialchars($parent_titles[$parent_id]),'post_id'=>$parent_id, 'img_src'=>$imgurl, 'width'=>$img_width, 'height'=>$img_height);                   
    }
    return $selection;
    

    So basically, first grab one largish result set with all published posts in the categories. Then a bunch of smaller queries, fetching a single attachment ID every loop until the $limit has been filled.

    If you’ve got lots of posts in these categories without attachments, you’ll waste some time here. But in our case it seems to be manageable.

    Still looking for that efficient single-query solution though. 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
Does anyone know how can I replace this 2 symbol below from the string
I used javascript for loading a picture on my website depending on which small
link Im having trouble converting the html entites into html characters, (&# 8217;) i
Basically, what I'm trying to create is a page of div tags, each has
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.