(Sorry if the title is pretty useless)
I have this function to get the first image from a random post in WordPress. This works great, but now I need it to select a random image from all the matches, rather than the first.
(I’m running this function in a query_posts loop to select the categories)
// Get first image in post
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
//no image found display default image instead
if(empty($first_img)){
$first_img = "/images/default.jpg";
}
// Or, show first image.
return $first_img;
}
So, any ideas, links, tips & tricks on how to select a random result from the matches results?
Match everything, and then use array_rand() to get a random match.
Assuming you use the PREG_SET_ORDER flag with preg_match_all then to get a random link.
It is important to note that
array_rand()
returns a random key, not a random value.Try with this
You should be able to use
array_rand()
to return a random key from the$matches
array. You may need to change the format of the array you get frompreg_match_all()
.You can use
PREG_PATTERN_ORDER
then pass$matches[$x]
toarray_rand()
– where$x
is the match group you want (0 being the full match, 1 being the first subgroup). In this casearray_rand()
will return a key, and you can access the random data using$matches[$x][$rand_key]
.Alternatively, using
PREG_SET_ORDER
, you would pass$matches
toarray_rand()
, then use the returned key to access any subgroup of the match.$matches[$rand_key][$x]
Note that you’re not getting a random value, you’re getting the array key to a random value. And as noted by others, you can simply use the
array_rand()
function directly when accessing the array, which is an easy cut/paste solution. However, I hope this longer explanation sheds light on what the code is doing.