How to Create Random Image from Post Thumbnails WordPress

WordPress provide feature to show your post randomly. You can find many tutorials talk about it. But, sometimes your emphasize in viewing images other than words. It happen when your sites talk about interior, artistic, photographic, or displaying products. By viewing random images, you can make your last photos, products, or designs visible together with your new images.

WordPress Random Image Tutorial

See Live Demo

Step 1. Edit function.php

Now, let’s begin to make it. First we need add two function in function.php. These are:

  1. PostThumbURL() function to get image URL from featured image (post-thumbnail URL) and
  2. catch_that_image() to get image URL from the first image in the post.

Here the code

function PostThumbURL() {
	global $post, $posts;
	$thumbnail = '';
	ob_start();the_post_thumbnail();$toparse=ob_get_contents();ob_end_clean();
	preg_match_all('/src=("[^"]*")/i', $toparse, $img_src); $thumbnail = str_replace("\"", "", $img_src[1][0]);
	return $thumbnail;
} 
function catch_that_image() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/ltimg.src'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];
  return $first_img;
}

Because we need post-thumbnails feature, we have to enable it by this code in function.php.

add_theme_support( 'post-thumbnails' );  

Step 2. Style the CSS

Next we need css to make nice view for images.

.thumb img{
width: 150px; 
height: 110px;
padding:5px;
margin:0px 0px 0px 0px;
border:1px solid #e9e9e9;
float:left;
}
.thumb a:hover img{
border:1px solid #9a9a98;
}

Step 3. Core Code

Now, let’s begin to make the core code. In this code, we try to view image from posts having featured image using PostThumbURL() or image in the post using catch_that_image().

<?php
	//define number (in this case six posts) of random post  
	$args = array( 'numberposts' => 6, 'orderby' => 'rand' );
	$rand_posts = get_posts( $args );
?>
<?php foreach( $rand_posts as $post ) : ?>
	<!-- #if the post have post thumbnail image -->
	<?php if (has_post_thumbnail()){?>
		<div class="tumbImage"> 
			<a href="<?php the_permalink(); ?>"> 
				<!-- #get image from post thumbnail -->
				<img  src="<?php echo PostThumbURL(); ?>" /> 
			 </a> 
		</div>
	<!-- #if the post does not have post thumbnail image -->
	<!-- #Get posts having image in the post and get the first one-->

	<?php }  else if (catch_that_image()) {?>
		<div class="tumbImage"> 
			<a href="<?php the_permalink(); ?>"> 
				<!-- #get image from post content -->
				<img src="<?php echo catch_that_image(); ?>" /> 
			</a> 
		</div>
	<?php } ?>
<?php endforeach; ?>

Then you can put this code on everywhere you want to display your random images, as you can see on the live demo page we put this code on header.php and footer.php.

Explanation of the code
In this code, we get six posts and we define to view them randomly. Then, we make looping and make selection for the post. If the post has featured image (post thumbnail image), we will display the image and give a link going to the detail post in the image. If the post does not have featured image, we will make selection again, whether the post has image in the post, then display the first one and give a link in the image.

Hopefully this tutorial useful for you :D.

See Live Demo

8 Comments to “How to Create Random Image from Post Thumbnails WordPress”

Add Comments (+)

  1. designfollow says:

    I use this function all the time on my sites, works great!

    thanks mr_alfan.

  2. I usually add rand to the query, looking forward to trying this function. Thanks for the share.

  3. mr_alfan says:

    @designfollow, @elliot : We’re glad this post helpful, stay tune with our next tutorials :)

  4. leader says:

    We learned something newjust now now I’m good for today. Thanks!

  5. simonpodcaster says:

    Hi Alfan! Thank you very much for this little tutorial! It’s awesome!!! I need to get Random Image from a specific category. What do you think I have to do? Thank’s in advance!

  6. simonpodcaster says:

    Hi again Alfan! I think I found the solution. I just add the parameter ‘category_name’ => ‘modelos’ into the $args parameters. So, the code must to be –>   $args = array( ‘numberposts’ => 2, ‘orderby’ => ‘rand’, ‘category_name’ => ‘example’ );Thank you again! ^^

  7. simonpodcaster says:

    Hi again Alfan! I think I found the solution. I just add the parameter ‘category_name’ => ‘example’ into the $args parameters. So, the code must to be –>   $args = array( ‘numberposts’ => 2, ‘orderby’ => ‘rand’, ‘category_name’ => ‘example’ );
     
    Thank you again! ^^

  8. Time Clock says:

    Thanks…Let me try this and get back to you with the feedback.

Leave a Reply

 

Amazingly Beautiful WordPress Themes