Back WordPress

How to Create Random Image from Post Thumbnails WordPress

WRITTEN BY ON 08 Mar 2012

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.


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.

	//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(); ?>" />
	<!-- #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(); ?>" />
	<?php } ?>
<?php endforeach; ?>
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.