My own piece of the Internet
 
Random default thumbnails for Yet Another Related Posts Plugin

Random default thumbnails for Yet Another Related Posts Plugin

I installed the Yet Another Related Posts Plugin (YARPP) and was frustrated by the stripey default thumbnail that was displayed if a post didn’t have a featured image. Unfortunately for me, this was quite a few. So what I ended up with was:

Pretty ugly.

So I did some pretty basic hacking and created a pretty awesome (just ask me) way of displaying random thumbnails if there isn’t a featured image associated with a post. Here’s what it looks like:

Before I continue I need to offer a disclaimer – I am no coder so if you find anything here that could be improved please let me know.

First I created a bunch of 120px x 120px thumbnails that featured people I think have made a difference in the world. Yes, even Prof. Freud.

I uploaded these to a directory wp-content/uploads/default-yarpp/.

Next I added a basic function to related-functions.php which is located in the YARPP plugin directory.

function getRandomDefaultThumb() {
$blogurl = get_bloginfo('url');
$thumbsDir = 'wp-content/uploads/default-yarpp/';
$thumbs = glob($thumbsDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

 if ( $thumbs != '' ) 
 {
 $randomThumb = $blogurl . '/' . $thumbs[array_rand($thumbs)]; 
 }

 return $randomThumb;
}

Then, I copied yarpp-template-thumbnail.php into my theme directory and chose custom PHP in the YARPP options. I modified this by changing the following:

$output .= '<span><img src="' . esc_url($thumbnails_default) . '"/></span>';

to

$output .= '<span><img src="' . esc_url(getRandomDefaultThumb()) . '"/></span>';

All done.

It could be enhanced by somehow reading the tags of the posts and then selecting a random image which has that same tag in the filename, but, well that would be a lot of work and as I said, I am no coder. Having said that, being creative and solving problems is a lot of fun.

Subscribe to my infrequent updates

What do you think?