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.

PHP

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.

<?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; ?>

Share the love

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement