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 wp_postmeta.meta_value=wp_posts.id 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)
continue;
if ($img1=='') {
$img1=$img_src[0];
} elseif ($img2=='') {
$img2=$img_src[0];
break;
}
}
}
return (array($img1,$img2));
}

Join 164 other subscribers

Archives

  • 2024 (3)
  • 2023 (8)
  • 2022 (15)
  • 2021 (19)
  • 2020 (1)
  • 2019 (1)
  • 2018 (2)
  • 2017 (1)
  • 2016 (2)
  • 2015 (5)
  • 2014 (5)
  • 2013 (2)
  • 2011 (7)
  • 2010 (10)
  • 2009 (50)
  • 2008 (28)
  • 2007 (31)
  • 2006 (8)

Category