A Faster Random Image for Gallery2
For some reason the Random Image block was sometimes taking 6-10 seconds to load an image from my gallery of just over 1,000 images.
I couldn’t really figure out why this was happening, so I made it optional to view the block. However, I like the random image so I was thinking about it a little bit and found a way to lower the time quite a bit; I created my own queries to get the directory data required to view the image.
I have the mod_rewrite module enabled, and since I wanted to retain that when the image was clicked on, I had to do a little extra work.
Previously, this is what I would have done to show the random image, which would result in random spikes of 6-10 second loads.
<?php
@readfile('http://raydehler.com/photos/main.php?g2_view=imageblock:External&g2_blocks=randomImage&g2_show=title');
?>
After snooping through the code and the database for a couple of hours, I was finally able to come up with a working replica that has not yet randomly lagged.
//we want to find only the pictures that are "thumbnails"
//http://dev.mysql.com/doc/mysql/en/string-functions.html for INSTR
$sql = $wpdb->get_row("SELECT g2_Derivative.g_id, g_derivativeSourceId, g_pathComponent
FROM `g2_Derivative`, `g2_FileSystemEntity`
WHERE INSTR(g2_Derivative.g_derivativeOperations, 'thumbnail') != 0
AND g_derivativeSourceId = g2_FileSystemEntity.g_id
ORDER BY RAND() LIMIT 1");
$url = "";
$tmp = $sql->g_derivativeSourceId;
//recursive parent backtracking
while($tmp != "0"){ //$tmp = 0 at the top level
$sql2 = $wpdb->get_row("SELECT g2_FileSystemEntity.g_pathComponent, g2_ChildEntity.g_parentId
FROM g2_FileSystemEntity, g2_ChildEntity
WHERE g2_FileSystemEntity.g_id = g2_ChildEntity.g_id
AND g2_FileSystemEntity.g_id = '$tmp'");
$tmp = $sql2->g_parentId;
$url = $sql2->g_pathComponent."/".$url;
}
$wpdb is an instance of Wordpress’s database class, it just gives the result in an array and adds the queries to the query counter.
Feel free to use this script if you are also having speed issues, and please comment if you do use it.

Raybdbomb Said,
June 28, 2005 @ 2:09 pm
I’ve noticed how it sometimes will show a “thumbnail” of a video. There’s an easy fix for this, but it would be so hard to test and make sure it worked. I won’t worry about it (unless someone wants me to fix it). So I’ll throw that in as a “known bug” or “minor bug”.