php, sql, WordPress

Random featured images in wordpress

I’ve had random header images on the Fedibblety Family blog for quite some time. I originally implemented this by looking for images in a particular directory. However, I had to manually add pictures to this directory, which was a bit cumbersome. I started thinking, why not just select randomly from all the featured images I have for my posts? So I hacked up a quick function to do that. Here it is:

function get_random_header_images() {
  global $wpdb;
  $featured_image_query = "select id from wp_postmeta join wp_posts on where meta_key='_thumbnail_id' order by rand() limit 10";
  $img1 = '';
  $img2  = '';
  $featured_images = $wpdb->get_results($featured_image_query);
  foreach ($featured_images as $img) {
    $img_src = wp_get_attachment_image_src( $img->id, 'medium');
    $ratio = $img_src[1] / $img_src[2];
    if ($ratio > 1.3 and $ratio < 1.6) {
      // make sure that the image isn't too big, and that it has been scaled by WordPress
      if ($img_src[1] > 250 or preg_match("/[0-9]+x[0-9]+/", $img_src[0]) == 0)
      if ($img1=='') {
      } elseif ($img2=='') {
  return (array($img1,$img2));